Check Natural Number in PHP

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Integers

What You’ll Learn

Under this tutorial’s definition, a natural number is a positive integer: n > 0. This page covers the one-comparison check, printing a counting range, CLI validation, a live preview, worked PHP examples, edge cases, and complexity.

Definition

n > 0

Counting numbers 1, 2, 3, … — zero is out under our rule.

One Test

isNatural

Return true when the integer is strictly positive.

Yes / No

Sample 42

Print a clear sentence for one fixed value.

Range List

1..10

Print a slice of counting numbers in order.

Live Preview

Try values

Check 42, 0, or -3 under the same rule.

O(1) Check

O(k) range

One comparison for a single test; linear to print a range.

Introduction

Natural numbers are the counting numbers you use for “how many?” — 1, 2, 3, and so on. In this lesson we treat natural as the same as positive integer: the integer must be strictly greater than zero.

Some textbooks include 0. Your program must follow the definition your teacher or spec states. Here the code uses $num > 0, so zero and negatives fail the test.

Why it matters?

It is a classic validation warm-up: state a definition, encode it as a comparison, and discuss edge cases like zero in interviews or exams.

Key Highlights

Rule Used

Integer with $n > 0.

Zero Debate

State whether 0 counts before coding.

Two Patterns

Single check or print a counting range.

Integers Only

Decimals are out of scope for this page.

In short: for an integer $num, answer yes when $num > 0; otherwise no — and say so clearly in the output.

📝 Problem & Approach

Given an integer, decide whether it is natural under the rule num > 0, and optionally print counting numbers in a range.

php
// 42  -> natural (42 > 0)
// 0   -> not natural under n > 0
// -3  -> not natural

Inputs & Outputs

ItemTypeDescription
$numintInteger to classify.
Returnbooltrue if natural under n > 0.
Printed outputtextYes/no sentence, or a printed range.

Minimal workflow

Pseudocode
function isNatural(num):   // integer
    if num > 0:
        return true
    return false

Method comparison

DefinitionTestIncludes 0?
This page (school-style)$n > 0No
Some math texts$n >= 0Yes
Positive integer only$n > 0Same as this page

⚡ Quick Reference

GoalPattern
Core testreturn $num > 0;
Include zeroreturn $num >= 0; (only if required)
Print messageecho $number . " is a natural number.\n";
Print rangefor ($i = $start; $i <= $end; $i++)
Filter in rangeif ($i > 0) echo $i . " ";
CLI parse$raw = trim(fgets(STDIN));

📋 n > 0 vs n >= 0 vs Range Print

Same topic — different definitions and output shapes.

n > 0
positive only

This page — 0 is not natural

n >= 0
include zero

Use only when the syllabus includes 0

Range print
1..10 list

Show counting numbers without a yes/no

Interview tip
define 0

Ask whether zero counts before coding

Context

When This Problem Shows Up

Reach for a natural-number check when input validation or counting-number talk matters.

  1. Homework validation

    Accept only positive whole numbers before other logic.

  2. Interview warm-ups

    Definitions, comparisons, and edge talk about zero.

  3. Before loops

    Print 1..n only when n is a natural count.

  4. Sibling classifiers

    Pairs with even/odd and other integer checks.

  5. Not for floats

    Decimals need a different type and different rules.

Key benefit: a one-line definition that trains clear specs, boolean helpers, and edge-case discussion.

🔮 Live Preview

Uses the same rule as the code: natural means integer > 0.

Try 42, 0, or -3. Non-integers show a short error message.

Live result
Press “Check”.

Examples Gallery

Three complete PHP programs — single yes/no check, print 1 through 10, and CLI input with validation. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and one sample value.

Example 1 — Yes / No for One Integer

Helper check with sample value 42 and a clear yes/no output line.

php
<?php
function isNatural(int $num): bool
{
    return $num > 0;
}

$number = 42;

if (isNatural($number)) {
    echo $number . " is a natural number.\n";
} else {
    echo $number . " is not a natural number.\n";
}
?>

How It Works

Change $number to 0 or a negative value to see the other branch. The helper is a single comparison — easy to explain aloud in an interview.

⚡ List Counting Numbers

Print a slice of the naturals without testing each value by hand.

Example 2 — Print from 1 to 10 in Order

Lists the counting numbers from 1 through 10 on one line.

php
<?php
function printNaturalsInRange(int $start, int $end): void
{
    echo "Natural numbers in the range $start to $end:\n";
    for ($i = $start; $i <= $end; $i++) {
        if ($i > 0) {
            echo $i . " ";
        }
    }
    echo "\n";
}

printNaturalsInRange(1, 10);
?>

How It Works

The loop walks every integer in the closed range; the $i > 0 filter keeps only naturals under our definition. If $start could be below 1, that filter (or clamping) keeps the output honest.

⚙️ Read From the User

Same helper; the value comes from STDIN with a numeric check.

Example 3 — Check a Number You Type

Reads one integer, rejects non-numeric input, then classifies with isNatural.

php
<?php
function isNatural(int $num): bool
{
    return $num > 0;
}

echo "Enter an integer: ";
$raw = trim(fgets(STDIN));

if (!is_numeric($raw) || strpos($raw, ".") !== false) {
    echo "Please enter a whole number.\n";
    exit(1);
}

$number = (int)$raw;

if (isNatural($number)) {
    echo $number . " is a natural number.\n";
} else {
    echo $number . " is not a natural number.\n";
}
?>

How It Works

Validate before casting so decimals and letters do not silently become integers. Under our definition, typed 0 correctly prints “not a natural number.”

🧠 How the Algorithm Decides

1

Get an integer

Use a literal, or read CLI input and validate it.

Input
2

Compare to zero

If $num > 0, it is natural under this lesson’s rule.

Test
3

Report clearly

Print a yes/no sentence a human can read.

Output
=

Classification done

The value is labeled natural or not under the chosen definition.

🔎 Worked Walkthrough — Sample Values

Apply $num > 0 to a few integers.

$numTestResult
4242 > 0natural
11 > 0natural
00 > 0not natural (here)
-3-3 > 0not natural

If your course includes zero, change the test to >= and update the wording together.

Use Cases

Where natural-number checks show up beyond the interview prompt.

1. Input Guards

Accept only positive whole counts.

Example: number of items > 0.

2. Exam Definitions

State whether 0 is included, then code.

Example: > vs >= choice.

3. Range Demos

Print 1..n as counting numbers.

Example: Example 2 pattern.

4. Before Other Checks

Ensure n is natural before factorial or tables.

Example: reject 0 for some prompts.

5. Complexity Talk

O(1) for one test; O(k) to print k values.

Example: range length end-start+1.

6. Boolean Helpers

Practice returning true/false cleanly.

Example: isNatural($n).

Pro Tip: open with “I’ll treat natural as n > 0 unless you include zero” before writing the comparison.

Advantages

Why this tiny check still earns interview points.

  1. 1. Tiny and Clear

    One comparison encodes the whole definition.

  2. 2. Easy to Adapt

    Flip to >= if the syllabus includes zero.

  3. 3. Composes Well

    Reuse isNatural before loops, tables, or factorials.

  4. 4. Constant Cost

    O(1) time and space for a single classification.

Pro Tip: keep the helper boolean and put human wording in the echo layer, not inside the math.

Usage Tips

Small habits that keep natural-number solutions interview-ready.

  1. 1. State the Definition

    Say whether zero counts before writing > or >=.

  2. 2. Keep Helpers Boolean

    Return true/false; print messages outside.

  3. 3. Validate CLI Input

    Reject non-integers before casting.

  4. 4. Filter Range Starts

    If $start can be ≤ 0, filter or clamp.

  5. 5. Test Zero Explicitly

    Always dry-run 0 under your chosen definition.

Pro Tip: check 42, 0, and -3 aloud — those three cases catch almost every beginner mistake.

Common Pitfalls

Mistakes that commonly break natural-number solutions.

  1. 1. Forgetting the Zero Debate

    Assuming every teacher includes or excludes 0.

    → Align the comparison with the stated definition.

  2. 2. Accepting Decimals Silently

    Casting 1.5 to 1 without complaining.

    → Validate whole-number input on CLI paths.

  3. 3. Printing Negatives in Ranges

    Looping from a negative start without filtering.

    → Keep the $i > 0 guard (or clamp start).

  4. 4. Mixing Messages and Math

    Hard-coding “natural” strings inside every caller.

    → Centralize the boolean test in isNatural.

  5. 5. Using >= Without Saying So

    Including zero while the prompt said positive only.

    → Match operator and wording to the spec.

Edge Cases

Handle these before calling the check done.

Zero

num == 0

Not natural under n > 0; may be natural if your syllabus includes 0.

Negative

num < 0

Always fails this lesson’s test.

One

num == 1

Smallest natural under the school-style definition.

Overflow

Very large int

Still an integer; the comparison works. Confirm limits for your PHP runtime if needed.

Decimals

Non-integers

Out of scope for int helpers — validate CLI input.

Range start

start ≤ 0

Filter with $i > 0 or clamp before printing.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Two conventions. ℕ sometimes starts at 0, sometimes at 1 — always confirm.
  • Positive integers. Under this page, natural ≡ positive integer.
  • Closed under addition. Sum of two naturals (starting at 1) is still natural.
  • Not closed under subtraction. 3 − 5 is negative, so not natural here.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Check three values

  • Run isNatural on 42, 0, and -3
  • Expect yes / no / no under n > 0

2. Include zero

  • Change the test to >=
  • Update messages so wording still matches

3. Print 1..20

  • Reuse Example 2 with end = 20
  • Confirm spacing and newline

4. CLI rejection

  • Reject 1.5 and abc
  • Accept -3 and classify it

Notes

  • Definition used: integer $n with $n > 0.
  • Patterns: one-off check plus optional range listing.
  • Remember: align code with the definition your exam uses (especially for 0).
  • User input: validate numeric whole numbers before calling isNatural.

Quick Takeaway: natural here means $n > 0 — say so, test zero, and print a clear sentence.

⏱️ Time and Space Complexity

OperationTimeExtra space
Single testO(1)O(1)
Print range start..endO(end - start + 1)O(1)
CLI parse + validateO(1)O(1)

The interesting part is the definition, not the asymptotic cost.

Wrap Up

🎉 Conclusion

Checking a natural number is a definition plus one comparison: under this page, return true when $num > 0. Extend the same helper to range printing and CLI validation without changing the core rule.

Practice the three examples above, then continue to number combinations.

State whether zero counts, then use > or >= — and test 0 explicitly.

💡 Best Practices

✅ Do

  • State whether 0 is included
  • Use a boolean isNatural helper
  • Validate CLI whole-number input
  • Dry-run 42, 0, and -3
  • Filter range prints with $i > 0 when needed

❌ Don’t

  • Assume every book excludes zero
  • Silently cast decimals to ints
  • Print negatives as naturals
  • Skip the zero test case
  • Mix definition and message text carelessly

Key Takeaways

Knowledge Unlocked

Five things to remember about natural numbers

Classify counting numbers the interview-friendly way.

5
Core concepts
0 02

Zero

Confirm first

Edge
? 03

Check

isNatural bool

Code
04

Range

Print 1..k

Pattern
O 05

Cost

O(1) / O(k)

Analysis

❓ Frequently Asked Questions

In this tutorial, it is a whole number you get when you count real things: 1, 2, 3, and so on. We treat "natural" as the same as "positive integer" (strictly greater than zero).
It depends on the book. Some definitions include 0; this program uses the test n > 0, so 0 is not natural here. If your course includes 0, change the test to n >= 0 and rename the message text to match your definition.
PHP supports booleans directly, so returning true for yes and false for no keeps the helper clear and readable.
The function takes an int. Numbers like 1.5 are not integers, so you would use a different type and different rules (this page stays with whole numbers).
They fail the n > 0 test, so the program says they are not natural numbers under our definition.
A single comparison is O(1) time. Printing a range from a to b costs O(b - a + 1) time for the loop body.
Only if your syllabus includes 0 in the naturals. State the definition first, then pick > or >= to match.
Under this page's definition they are the same: integer and greater than zero.

Did you Know? 🔊

In many school-level texts, natural numbers start at 1 (1, 2, 3, ...). Some mathematicians include 0; programs must follow whichever definition your teacher or spec states — here we use n > 0.

Continue to Number Combinations

Learn how to generate number combinations and pairs with nested loops in PHP.

Number combinations tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful