๐ŸŽ“ A1Learner
๐Ÿ”

PHP If Else

An if statement runs a block of code only when its test is true. The else block runs when that test is false.

An if block that runs

The age passes the test. The line inside the block prints.

<?php
$age = 20;
if ($age >= 18) {
  echo "Adult\n";
}

Two branches in one program

A branch is one path a program can take. Changing the age makes the second check take the other path.

<?php
$age = 20;
if ($age >= 18) {
  echo "First check says adult\n";
} else {
  echo "First check says young\n";
}
$age = 12;
if ($age >= 18) {
  echo "Second check says adult\n";
} else {
  echo "Second check says young\n";
}

An elseif chain grades a score

The tests run in order from the top. The first test that passes picks the line.

<?php
$score = 75;
if ($score >= 90) {
  echo "Grade A\n";
} elseif ($score >= 70) {
  echo "Grade B\n";
} else {
  echo "Grade C\n";
}

Example

<?php
$age = 10;
if ($age < 12) {
  echo "Child ticket\n";
  echo "Price is 5\n";
} elseif ($age < 65) {
  echo "Adult ticket\n";
  echo "Price is 12\n";
} else {
  echo "Senior ticket\n";
  echo "Price is 8\n";
}

Key points

  • An if statement lets a program choose its next lines from a test result.
  • The test goes inside parentheses after the word if.
  • Curly braces group the lines that belong to one branch.
  • The else block has no test of its own.
  • The elseif block tests a new condition when the earlier tests are false.
  • A test that is false skips the if block.

In this example, the age is 10. The first test asks whether 10 is below 12, and it is. The child label and the child price print. The other parts of the chain do not run.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

The test in an if statement is false, and the statement has an else block. Which block runs?