Table of Contents

PHP Conditionals

A conditional allows you to run a particular piece of code if a condition is met.

First lets make a variable:

$my_socks = 'blue';

First, we want to run an if statement to check if our socks are blue, and we want to print out a message. If not, we want to print out a different message. So let's create our first if statement:

if ( $my_socks == 'blue')

We put our condition in the parenthesis (). Notice we are using double equal == because if we use only one equal =, we are essentially assigning the value to the variable. So by using ==, we are comparing if that variable has this value.

if ( $my_socks == 'blue'){
    echo 'My socks are blue';
}

Inside the curly braces {} we put the code that we want to run if the condition is met.

if ( $my_socks == 'blue'){
    echo 'My socks are blue';
} else {
    echo 'My socks are not blue';
}

The else statement uses the same curly braces {}. We put the code that we want to run if the condition is not met. In our case, the condition is met, so we will see My socks are blue printed out.

We can also add the elseif statement. We can give it a second condition, which can have its own message.

if ( $my_socks == 'blue'){
    echo 'My socks are blue';
} elseif ( $my_socks == 'red') {
    echo 'My socks are red';
} else {
    echo 'My socks are not blue or red';
}