Skip to main content

PHP Conditional Statements

Programs constantly have to make decisions: if the user is logged in, show one thing; if not, show another. Conditional statements are how you tell PHP to choose between different actions.

PHP gives you these options:

  • if statement - runs a piece of code only when a condition is true
  • if...else statement - runs one piece of code when a condition is true and a different piece when it is false
  • if...elseif...else statement - chooses between different pieces of code when there are more than two conditions
  • switch statement - picks one block out of many to run

The if Statement

The simplest decision is an if: when its condition is true, the code inside the braces runs, and otherwise PHP skips it.

If Statement

Since 5 is greater than 3, the condition is true and the message is displayed:

Prompt
Write a PHP script that checks if 5 is greater than 3 and outputs a message if the condition is true.
Output: PHP script

Syntax

An if statement is written like this:

index.php
<?php
if (condition) {
  // code to be executed if condition is true;
}
?>

Indentation

Indenting the code inside an if block is optional as far as PHP is concerned. Do it anyway, since it is considered good practice and makes the structure much easier to read.

Indentation Example

The echo line below is indented to show that it belongs to the if block:

Prompt
Write a PHP script that uses an if statement with proper indentation to check if a number is positive and outputs a message.
Output: PHP script

Multiple Conditions

A single if can test several conditions at once. Join them with the && or || operators, and add as many as you need:

And Operator

Both checks have to pass here: $a must be above $b and, at the same time, below $c:

Prompt
Write a PHP script that uses the && operator to test if a variable is greater than one value and less than another, then outputs a message.
Output: PHP script

Or Operator

One passing check is enough with OR. Here $a would need to be 2 or 3, but it is 5, so the else block runs:

Prompt
Write a PHP script that uses the || operator to test if a variable equals one value or another, then outputs a message.
Output: PHP script