How to use conditionals in PHP

I previously introduced comparison operators: <, >, <=, >=, ==, === , !=, !==… and so on!

Those operators are going to be super useful for one thing: conditionals.

Conditionals are the first control structure we see.

We can decide to do something, or something else, based on a comparison.

For example:

$age = 17;

if ($age > 18) {
  echo 'You can enter the pub';
}

The code inside the parentheses only executes if the condition evaluates to true.

Use else to do something else in case the condition is false:

$age = 17;

if ($age > 18) {
  echo 'You can enter the pub';
} else {
  echo 'You cannot enter the pub';
}

NOTE: I used cannot instead of can't because the single quote would terminate my string before it should. In this case you could escape the ' in this way: echo 'You can\'t enter the pub';

You can have multiple if statements chained using elseif:

$age = 17;

if ($age > 20) {
  echo 'You are 20+';
} elseif ($age > 18) {
  echo 'You are 18+';
} else {
  echo 'You are <18';
}

In addition to if, we have the switch statement.

We use that when we have a variable that could have a few different values, and we don’t have to have a long if / elseif block:

$age = 17

switch($age) {
  case 15:
		echo 'You are 15';
    break;
  case 16:
		echo 'You are 16';
    break;
  case 17:
		echo 'You are 17';
    break;
  case 18:
		echo 'You are 18';
    break;
  default:
    echo "You are $age";
}

I know the example does not have any logic, but I think it can help you understand how switch works.

The break; statement after each case is essential. If you don’t add that and the age is 17, you’d see

You are 17
You are 18
You are 17

Instead of just

You are 17

as you’d expect.

Download my free PHP Handbook!