facebook twitter
Webucator's Free PHP Tutorial

Lesson: PHP Conditionals

Welcome to our free PHP tutorial. This tutorial is based on Webucator's Introduction to PHP Training course.

Conditional processing allows programmers to execute different code based on specific conditions. There are two conditional structures in PHP - if - elseif - else and switch / case. There is also a special operator called the ternary operator for short conditional expressions.

Lesson Goals

  • To work with if - elseif - else conditions in PHP.
  • To work with switch / case statements in PHP.
  • To use the ternary operator.
  • To use the null coalescing operator.

if / if - else / if - elseif - else

Conditional statements are used to determine whether or not to run a block of code or to decide which block of code to execute.

Simple if Condition

The syntax for a simple if condition is as follows:

if (expression) {
  doThis();
  doThat();
  doThisOtherThing();
}

The lines of code affected by the if condition are put in a code block, which is surrounded by curly brackets to indicate that all of the code either should or should not be executed depending on the true-false value of the expression.

if-else Condition

The syntax for an if-else condition is as follows:

if (expression) {
  doThis();
} else {
  doThat();
}

In the code above, either doThis(); or doThat(); will run depending on the true-false value of the expression.

if-elseif-else statement

The syntax for an if - elseif - else condition is as follows:

if (expression) {
  doThis();
} elseif (otherExpression) {
  doThat();
} else {
  doThisOtherThing();
}

An if - elseif - else condition can have any number of elseif blocks, but only zero or one else blocks.

Comparison Operators

The following table shows PHP's comparison operators:

Comparison Operators
Operator Description
== Equals
=== Identical (same value and same type)
!= Doesn't equal
!== Not identical
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to

Note the difference between == (equals) and === (identical). For two objects to be identical, they must be of the same value and the same type, whereas to be equal, they must only have the same value. For example, 1 is equal to, but not identical to, "1".

It is almost always better to use the identical operator (===) and the corresponding not identical operator (!==) as these help avoid unanticipated errors.

The following example demonstrates an if - elseif - else statement:

Code Sample:

Conditionals/Demos/if.php
---- C O D E   O M I T T E D ----
<?php
$age = 21;
if ($age >= 21) {
  echo 'You can vote and drink!';
} elseif ($age >= 18) {
  echo 'You can vote, but can\'t drink.';
} else {
  echo 'You cannot vote or drink.';
}
?>
---- C O D E   O M I T T E D ----

Code Explanation

The file is relatively simple. You can see the different results by changing the value of $age and visiting http://localhost:8888/Webucator/php/Conditionals/Demos/if.php.

Compound If Statements

More complex if statements often require that several conditions be checked. The table below shows and and or operators for checking multiple conditions and the not operator for negating a boolean value (i.e, turning true to false or vice versa).

Logical Operators
Operator Name Example
&& AND $a && $b
|| OR $a || $b
! NOT !$b

The following example shows these logical operators in practice:

Code Sample:

Conditionals/Demos/if-2.php
---- C O D E   O M I T T E D ----
<?php
$age = 21;
$citizen = false;
if ($age >= 21 && !$citizen) {
  echo 'You can drink, but can\'t vote.';
} elseif ($age >= 21) {
  echo 'You can vote and drink!';
} elseif ($age >= 18 && $citizen) {
  echo 'You can vote, but can\'t drink.';
}  else {
  echo 'You cannot vote or drink.';
}
?>
---- C O D E   O M I T T E D ----

False Equivalents: Falsy Values

PHP can change the type of a value on the fly. For example, the following expression will evaluate to 10:

5 + '5'

Every expression in PHP can be converted to a boolean value (true or false). For example, the value 0, when treated like a boolean, is evaluated as false. All other numbers are evaluated as true. Examine the following code:

if (1) {
  // This code will run.
}

if (0) {
  // This code will NOT run.
}

Non-boolean values that are evaluated as false when treated as a boolean are called falsy. The list below shows the most common falsy values:

  1. The integer 0
  2. The float 0.0
  3. The string "0"
  4. An empty string: ""
  5. An empty array.
  6. NULL (a variable with no value).

To explicitly convert a value to a boolean, pass it to the built-in boolval() function:

boolval('0');

Note that when echo-ing the boolean false, it gets converted to an empty string, so nothing will show up in the browser. To force a value to show up, pass it to the var_dump() function:

echo var_dump(boolval('0'));

You will likely only need this function for testing purposes. To see this in action, review Conditionals/Demos/testing-booleans.php in your editor and run http://localhost:8888/Webucator/php/Conditionals/Demos/testing-booleans.php in your browser.

Testing for Variable Existence

In some cases, you won't be sure whether a variable has been declared and/or whether it has a non-null value. PHP provides built-in functions for checking if a variable exists, checking if a variable holds a value, and removing a variable.

Variable Existence
Function Explanation Example
isset() Returns true if a variable exists and has been set. Otherwise, returns false. isset($a)
empty() Returns true if the variable doesn't exist or contains a falsy value. Otherwise, returns false. empty($a)
unset() Removes a variable from memory. unset($a)

var_dump()

To output the results of these functions to a browser, use the var_dump() function (e.g. var_dump(isset($a));).

The isset() and empty() functions are close to opposites, which would make !empty() the same as isset(), but that's not quite true. !empty() returns true if the variable isn't set, but it also returns true if it is set to a falsy value (e.g., an empty string). The example below illustrates this:

Code Sample:

Conditionals/Demos/hello-hi.php
<?php
  if (isset($_GET['greeting'])) {
    $greeting1 = $_GET['greeting'];
  } else {
    $greeting1 = 'Hello';
  }

  if (!empty($_GET['greeting'])) {
    $greeting2 = $_GET['greeting'];
  } else {
    $greeting2 = 'Hello';
  }
?>
---- C O D E   O M I T T E D ----
<main>
  <h2>isset()</h2>
  <p><?= $greeting1 ?>, World!</p>
  <h2>!empty()</h2>
  <p><?= $greeting2 ?>, World!</p>
</main>
---- C O D E   O M I T T E D ----

Code Explanation

The screenshots below show different outcomes depending on whether and to what value $_GET['greeting'] is set:

  1. hello-hi.php?greeting=Hi: isset() vs !empty() - 1 In this case, there is no difference.
  2. hello-hi.php: isset() vs !empty() - 2 In this case, there is also no difference.
  3. hello-hi.php?greeting=: isset() vs !empty() - 3 In this case, there is a difference: $_GET['greeting'] is set, but it is not not empty (i.e., it is empty).

Variable Functions

For a complete list of variable functions see https://www.php.net/manual/en/ref.var.php.

Checking for Variable Existence

Duration: 15 to 20 minutes.

You will remember that we had an issue with the page title of our PHP Poetry site's home page: Title of index.php - warningIn this exercise, we will fix that issue.

  1. Open Conditionals/Exercises/phppoetry.com/includes/header.php in your editor.
  2. In the PHP block at the top, create a new variable called $pageTitleTag that will be used as the value of the <title> tag. Add code that checks for the existence of $pageTitle.
    1. If the $pageTitle variable exists, set $pageTitleTag to $pageTitle followed by ' | The Poet Tree Club'.
    2. If the $pageTitle variable does not exist, set $pageTitleTag to 'The Poet Tree Club'.
  3. Change the <title> tag, so that it just contains the value of $pageTitleTag.

Solution:

Conditionals/Solutions/phppoetry.com/includes/header.php
<?php
  require_once 'utilities.php';
  if (isDebugMode()) {
    ini_set('display_errors', '1');
  }
  
  if (empty($pageTitle)) {
    $pageTitleTag = 'The Poet Tree Club';
  } else {
    $pageTitleTag = $pageTitle . ' | The Poet Tree Club';
  }
?>
---- C O D E   O M I T T E D ----
<title><?= $pageTitleTag ?></title>
---- C O D E   O M I T T E D ----

Code Explanation

Now when you visit http://localhost:8888/Webucator/php/Conditionals/Exercises/phppoetry.com/index.php, the title should show up as 'The Poet Tree Club':Title of index.php - fixedOther pages should still have the prefixed title: Title of poems.php - fixed

switch/case

A switch/case statement is similar to an if statement, except that it can only check for an equality comparison of a single expression. It cannot, for example, be used to check if one value is higher than another.

Syntax

switch (expression)
{
  case 'a' :
    echo 'expression is a';
    break;
  case 'b' :
    echo 'expression is b';
    break;
  case 'c' :
    echo 'expression is c';
    break;
  default :
    echo 'expression is unknown';
}

The break statement is important. Without it, after a single match is found, all following statements will execute.

The following example demonstrates a switch/case statement without break statements:

Code Sample:

Conditionals/Demos/switch-no-break.php
---- C O D E   O M I T T E D ----
<?php
$quantity = 1;
switch ($quantity) {
  case 1 :
    echo '<p>Quantity is 1.</p>';
  case 2 :
    echo '<p>Quantity is 2.</p>';
  default :
    echo '<p>Quantity is not 1 or 2.</p>';
}
?>
---- C O D E   O M I T T E D ----

Code Explanation

The screenshot below shows the result:switch without break

Notice that, once a match is found, all remaining echo statements are output. The following example shows how this can be fixed by adding break statements:

Code Sample:

Conditionals/Demos/switch-with-break.php
---- C O D E   O M I T T E D ----
<?php
$quantity = 1;
switch ($quantity) {
  case 1 :
    echo 'Quantity is 1';
    break;
  case 2 :
    echo 'Quantity is 2';
    break;
  default :
    echo 'Quantity is not 1 or 2';
}
?>
---- C O D E   O M I T T E D ----

Code Explanation

This time, only the first statement is output:switch with break

Use Case for switch without break

In most cases, you will include break statements in your switch conditions; however, there are cases when it makes sense to continue to execute all the subsequent statements in a switch condition after a match has been found. Consider the following, in which permissions are being added to a list based on a user's role:

Code Sample:

Conditionals/Demos/switch-no-break-use-case.php
---- C O D E   O M I T T E D ----
  <p>You have the following permissions:</p>
  <ol>
<?php
$role = 'Admin';
switch ($role) {
  case 'SuperAdmin' :
    echo '<li>Delete</li>';
  case 'Admin' :
    echo '<li>Update</li>';
  case 'Contributor' :
    echo '<li>Create</li>';
  default :
    echo '<li>Read</li>';
}
?>
---- C O D E   O M I T T E D ----

Code Explanation

  • SuperAdmin will get all permissions.
  • Admin will get update, create, and read permissions.
  • Contributor will get create and read permissions.
  • All others will only get read permissions.

As we have set $role to "Admin", this will output the following:switch with break use case

Order of Conditions

In conditional statements, it's good practice to test for the most likely cases/matches first so PHP can find the correct code to execute more quickly.

Working with Conditions

Duration: 20 to 30 minutes.

In this exercise, you will create a page for handling a simple form submission.

  1. Open Conditionals/Exercises/greeting.html in your editor and review the code. This is the form that will be submitted. Filled out, it looks like this:Greeting Form This form is submitted using the get method, which means the form entries will be appended to the query string and will be accessible in the $_GET array.
  2. Open Conditionals/Exercises/greeting.php in your editor.
  3. Insert a PHP block that checks to see if the user filled out both the last-name and the dominant-hand fields in the form.
    • If the user failed to fill out either one of the fields, write out an error message to the screen:Greeting Form Error
    • If the user filled out both fields, return an appropriate greeting such as "Hello, Lefty Dunn!" or "Hello, Righty Dunn!"Greeting Form Success
  4. Try to use both an if condition and a switch statement in this exercise.
  5. Visit http://localhost:8888/Webucator/php/Conditionals/Exercises/greeting.html to test your solution in your browser. Submit the form with and without data.

Solution:

Conditionals/Solutions/greeting.php
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../static/styles/normalize.css">
<link rel="stylesheet" href="../../static/styles/styles.css">
<title>Greeting Page</title>
</head>
<body>
<main>
<?php
  if (empty($_GET['last-name']) || empty($_GET['dominant-hand'])) {
    echo '<h1>Error</h1>
          <p>You must fill out the form.
          Please <a href="greeting.html">try again</a>.</p>';
  } else {
    $lastName = $_GET['last-name'];
    $dominantHand = $_GET['dominant-hand'];
    switch($dominantHand) {
      case 'left' :
        echo "<p>Hello, Lefty $lastName!</p>";
        break;
      default :
        echo "<p>Hello, Righty $lastName!</p>";
    }
  }
?>
</main>
</body>
</html>

Ternary Operator

The ternary operator provides a shortcut for if conditions. The syntax is as follows:

$varName = (expression) ? $valueIfTrue : $valueIfFalse;

If the expression is true, $varName will be assigned $valueIfTrue. Otherwise, it will be assigned $valueIfFalse.

To illustrate, consider this if condition:

if (!empty($_GET['greeting'])) {
  $greeting = $_GET['greeting'];
} else {
  $greeting = 'Hello';
}

Using the ternary operator, it could be rewritten like this:

$greeting = empty($_GET['greeting']) ? 'Hello' : $_GET['greeting'];

For longer conditions, it can be more readable to break this across lines:

$greeting = empty($_GET['greeting'])
      ? 'Hello'
      : $_GET['greeting'];

Open Conditionals/Demos/hello-hi-ternary.php in your editor to see this code in a file.

The Ternary Operator

Duration: 10 to 15 minutes.

In this exercise, you will modify the $pageTitle check in header.php to use the ternary operator instead of an if condition.

  1. Open Conditionals/Exercises/phppoetry.com/includes/header.php in your editor.
  2. Change the if condition that you wrote in the earlier exercise to use the ternary operator instead.

Solution:

Conditionals/Solutions/phppoetry.com/includes/header-ternary.php
<?php
  require_once 'utilities.php';
  if (isDebugMode()) {
    ini_set('display_errors', '1');
  }
  
  $pageTitleTag = empty($pageTitle)
                ? 'The Poet Tree Club'
                : $pageTitle . ' | The Poet Tree Club';
?>
---- C O D E   O M I T T E D ----

Null Coalescing Operator

PHP 7 introduced the Null Coalescing Operator, the double question mark (??), which can be used to set a default value for a variable. It is particularly useful when you don't know if a superglobal variable is set. Consider the following code:

$greeting = $_GET['greeting'] ?? 'Hello';

If greeting is passed in on the query string, then $greeting will be set to its value. However, if it is not passed in, $greeting will get 'Hello'. This is shown in the following file:

Code Sample:

Conditionals/Demos/hello-hi-null-coalescing.php
<?php
  $greeting = $_GET['greeting'] ?? 'Hello';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../static/styles/normalize.css">
<link rel="stylesheet" href="../../static/styles/styles.css">
<title><?= $greeting ?>, World!</title>
</head>
<body>
<main>
<?php
  echo "<p>$greeting, World!</p>";
?>
</main>
</body>
</html>