Topic 19 of 48 · Full Stack Essentials

While, If condition, If else, else If

Lesson TL;DRTopic 4: While, If condition, If else, else If 📖 5 min read · 🎯 intermediate · 🧭 Prerequisites: javascriptbom, phpwithupdatedelete Why this matters Up until now, your code just runs top to bottom —...
5 min read·intermediate·php · loops · conditionals · while-loop

Topic 4: While, If condition, If else, else If

📖 5 min read · 🎯 intermediate · 🧭 Prerequisites: javascript-bom, php-with-update-delete

Why this matters

Up until now, your code just runs top to bottom — every line executes, no questions asked. But real programs need to think. Should this user get a discount? Is this score a pass or fail? Is today a weekend? That's where if, else if, and else come in — they let your code make decisions. Pair that with a while loop, and your program can keep checking and acting until a job is done. In this lesson, we'll build a PHP classifier that examines every number from 1 to 50 and sorts it by its mathematical properties — and you'll see decision-making in code click into place.

What You'll Learn

  • Understand and apply PHP's if, if else, and else if statements to branch program logic
  • Use a while loop to iterate over a numeric range
  • Write and call a custom isPrime() function that uses a for loop and sqrt()
  • Chain multiple conditions to classify numbers as prime, even, multiple of 5, or odd

The Analogy

Think of a traffic control tower routing incoming planes. The first question asked of every aircraft is the most important: "Is this a VIP flight?" — that's your if. If it isn't, the controller checks the next criterion: "Is it a commercial passenger jet?" — else if. If still no match, another check: "Is it cargo?" — another else if. If none of the special rules fire, the plane gets the default runway — else. The while loop is the tower's shift: it keeps processing new arrivals as long as planes are in the queue. The moment the queue is empty, the shift ends and the loop exits.

Chapter 1: Conditional Statements and Loop Statements

the trainer sketched four constructs on the board. These are the core tools for controlling program flow in PHP — and in virtually every other language you'll encounter.

Conditional Statements

  • if — executes a block of code when a specified condition evaluates to true
  • if else — executes one block when the condition is true, a different block when it is false
  • else if — chains a new condition to test only when all preceding conditions were false

Loop Statements

  • while — repeats a block of code for as long as a specified condition remains true; the condition is evaluated before each iteration

Together, these four constructs let you ask questions about data and keep asking them across a sequence of values — the foundation of almost every algorithm.

Chapter 2: The isPrime() Helper Function

Before the class could classify numbers, they needed a reliable way to test primality. A prime number is greater than 1 and divisible only by 1 and itself. The efficient approach: check divisors only up to the square root of the candidate — any factor larger than sqrt(n) must be paired with one smaller than it, so you never need to go further.

<?php

function isPrime($number) {
    if ($number <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}

?>

Walk through the logic:

  1. Any number ≤ 1 is immediately disqualified — return false.
  2. A for loop runs from 2 up to sqrt($number) (inclusive).
  3. Inside the loop, the modulo operator % checks for exact divisibility. If any $i divides $number evenly, it has a non-trivial factor — return false.
  4. If the loop finishes without finding a factor, the number is prime — return true.

Using sqrt() keeps this function fast: checking 1–50 only needs divisor candidates up to ~7.

Chapter 3: The while Loop with Chained if / else if / else

With isPrime() in hand, the class wired up the main classification loop. The range runs from $start = 1 to $end = 50. A counter variable $current begins at $start and increments by 1 each iteration.

<?php

// Define the range
$start = 1;
$end   = 50;

// Initialize the counter
$current = $start;

// Loop through the range
while ($current <= $end) {

    // Check if the number is prime
    if (isPrime($current)) {
        echo "$current is a prime number.<br>";

    } else if ($current % 2 == 0) {
        // Check if the number is even
        echo "$current is an even number.<br>";

    } else if ($current % 5 == 0) {
        // Check if the number is a multiple of 5
        echo "$current is a multiple of 5.<br>";

    } else {
        // If none of the above, it must be an odd number
        echo "$current is an odd number.<br>";
    }

    // Increment the counter
    $current++;
}

?>

Condition priority matters here. The chain evaluates top-to-bottom and stops at the first true branch:

  1. Prime? — most exclusive check, tested first.
  2. Even?$current % 2 == 0
  3. Multiple of 5?$current % 5 == 0 — only reached if the number is neither prime nor even (e.g., 25 is not prime and not even, so it lands here).
  4. Odd fallback — anything that cleared all three gates above is simply odd.

Notice that $current++ sits outside the conditional chain but inside the while block — every iteration must advance the counter or the loop runs forever.

Chapter 4: Putting It All Together

Here is the complete, self-contained PHP script combining isPrime() and the classification loop. Copy this directly into a .php file and run it.

<?php

function isPrime($number) {
    if ($number <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}

// Define the range
$start = 1;
$end   = 50;

// Initialize the counter
$current = $start;

// Loop through the range
while ($current <= $end) {

    // Check if the number is prime
    if (isPrime($current)) {
        echo "$current is a prime number.<br>";

    } else if ($current % 2 == 0) {
        // Check if the number is even
        echo "$current is an even number.<br>";

    } else if ($current % 5 == 0) {
        // Check if the number is a multiple of 5
        echo "$current is a multiple of 5.<br>";

    } else {
        // If none of the above, it must be an odd number
        echo "$current is an odd number.<br>";
    }

    // Increment the counter
    $current++;
}

?>

Expected output (partial):

1 is an odd number.
2 is a prime number.
3 is a prime number.
4 is an even number.
5 is a prime number.
6 is an even number.
7 is a prime number.
...
25 is a multiple of 5.
...

Here is a flow diagram showing how each number moves through the decision chain:

flowchart TD
    A([Start: current = 1]) --> B{current <= 50?}
    B -- No --> Z([End])
    B -- Yes --> C{isPrime?}
    C -- Yes --> D[echo: prime]
    C -- No --> E{current % 2 == 0?}
    E -- Yes --> F[echo: even]
    E -- No --> G{current % 5 == 0?}
    G -- Yes --> H[echo: multiple of 5]
    G -- No --> I[echo: odd]
    D --> J[current++]
    F --> J
    H --> J
    I --> J
    J --> B

🧪 Try It Yourself

Task: Extend the classifier to also detect multiples of 3 (but not already classified as prime or even).

  1. Save the complete script above as classify.php in your local PHP server's document root (e.g., htdocs/ for XAMPP or www/ for WAMP).
  2. Add a new else if branch between the even check and the multiple-of-5 check:
} else if ($current % 3 == 0) {
    echo "$current is a multiple of 3.<br>";
}
  1. Run the script in your browser at http://localhost/classify.php.

Success criterion: You should see lines like 9 is a multiple of 3. and 15 is a multiple of 3. appearing in the output, while numbers like 6 (even) and 3 (prime) retain their original classifications.

🔍 Checkpoint Quiz

Q1. Why does the isPrime() function use sqrt($number) as the upper bound of its for loop instead of $number - 1?

A) Because sqrt() is a PHP built-in and runs faster
B) Because any factor larger than the square root would be paired with one already found below it, so there's no need to check further
C) Because numbers above their square root are automatically odd
D) To avoid integer overflow on large numbers

Q2. Given the following snippet, what is printed when $current = 15?

if (isPrime($current)) {
    echo "$current is a prime number.<br>";
} else if ($current % 2 == 0) {
    echo "$current is an even number.<br>";
} else if ($current % 5 == 0) {
    echo "$current is a multiple of 5.<br>";
} else {
    echo "$current is an odd number.<br>";
}

A) 15 is a prime number.
B) 15 is an even number.
C) 15 is a multiple of 5.
D) 15 is an odd number.

Q3. The while loop in the script never terminates if which line is accidentally removed?

A) $start = 1;
B) $current = $start;
C) $current++;
D) $end = 50;

Q4. You need to add a check for multiples of 7 to the classification chain. Where in the else if chain should you place it, and why does position matter?

A1. B — If n = a × b and both factors are greater than sqrt(n), their product would exceed n, which is impossible. So one factor is always ≤ sqrt(n); checking up to that point is sufficient.

A2. C — 15 is not prime (3 × 5), not even (15 % 2 = 1), but is a multiple of 5 (15 % 5 = 0), so the third branch fires and prints 15 is a multiple of 5.

A3. C — Without $current++, the counter never advances. The condition $current <= $end stays true forever, and the loop runs indefinitely (infinite loop).

A4. Place it after the even check (% 2 == 0) and before or after the multiple-of-5 check — order between those two doesn't affect correctness, but it must come after the prime check. Position matters because PHP evaluates if / else if branches top-to-bottom and stops at the first true — placing a broader or lower-priority check above a narrower one would swallow numbers that should have matched the earlier condition.

🪞 Recap

  • if executes a block when its condition is true; else if chains additional conditions; else catches everything that failed all prior checks.
  • A while loop repeats its body as long as its guard condition is true — always ensure the loop variable changes each iteration to avoid infinite loops.
  • The isPrime() function uses a for loop bounded by sqrt($number) to efficiently test for prime divisors.
  • Condition order in an if / else if / else chain is significant — the first matching branch wins and the rest are skipped.
  • The modulo operator % is the key tool for divisibility checks (even, multiple of 5, prime factoring).

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.