Skip to main content

PHP Nested If

The code inside an if block can be anything, including another if. Placing one inside the other gives you what are known as nested if statements.

Nested if

The inner if is only reached if the outer condition is true, so here $a has to pass both tests before the message appears:

Prompt
Write a PHP script that sets a variable $a to 30. Use a nested if statement: the outer if checks if $a is greater than 10, and inside that, a second if checks if $a is also greater than 20. If both are true, echo "Above 10, and also above 20.".
Output: PHP script

Nested if...else

An inner if can have its own else block as well. Here it would run if $a were above 10 but not above 20:

Prompt
Write a PHP script that sets a variable $a to 30. Use a nested if...else: the outer if checks if $a is greater than 10 (if not, echo "Above 10, "). Inside the true branch, check if $a is greater than 20 and echo "and also above 20." if true, or echo "but not above 20." if false.
Output: PHP script