Look at the PHP code below. What will it print?
<?php $number = 10; if ($number > 10) { echo "Greater than 10"; } elseif ($number == 10) { echo "Equal to 10"; } else { echo "Less than 10"; } ?>
Check the condition that matches the value 10 exactly.
The variable $number is 10. The first condition ($number > 10) is false. The second condition ($number == 10) is true, so it prints "Equal to 10".
Consider this PHP snippet. What is printed?
<?php $value = 0; if ($value) { echo "True"; } else { echo "False"; } ?>
Remember how PHP treats 0 in conditions.
In PHP, 0 is considered false in a condition, so the else block runs and prints "False".
Look at this PHP code. It prints nothing. Why?
<?php $score = 75; if ($score > 80); { echo "Passed"; } ?>
Check the semicolon after the if condition.
The semicolon after the if condition ends the if statement. The block after it runs always, so "Passed" is printed regardless of the condition.
What does this PHP code print?
<?php $age = 20; if ($age > 18) { if ($age < 21) { echo "Young adult"; } else { echo "Adult"; } } else { echo "Minor"; } ?>
Check both conditions carefully.
$age is 20, which is greater than 18 and less than 21, so it prints "Young adult".
Consider this PHP code. How many times will it print something?
<?php $val = 5; if ($val > 3) { echo "A"; } elseif ($val > 4) { echo "B"; } else { echo "C"; } ?>
Remember that only one block in if-elseif-else runs.
The first condition ($val > 3) is true, so it prints "A" and skips the rest. Only one echo runs.