The majority of the time your PHP application or script will vary depending on different conditions. These conditions can be set via the script itself, or from user interaction – regardless your PHP script needs a way to handle these different situations. This is where conditional statements in PHP are introduced.
PHP has several different conditional statements:
- if statement – executes some code only if a specified condition is true
- if…else statement – executes some code if a condition is true and another code if the condition is false
- if…elseif….else statement – selects one of several blocks of code to be executed based on the condition
- switch statement – selects one of many blocks of code to be executed
IF Statements
Let’s start with the most basic of the bunch. The if statement. The if statement evaluates the truth value of it’s condition and if the condition evaluates as TRUE the code following the if statement will be executed.
So in the above example we will get the display Name is Mike because the variable $name
is set to Mike, and inside our if statement we set the condition so that if the $name
variable is set to Mike
PHP will echo the statement Name is Mike.
However if we changed our $name
variable to Eric for example – then our script would not produce anything. To fix this we can use the else
statement.
IF…ELSE Statements
Now if our initial condition checking for the value of the $name
variable to be Mike
returns false we will echo out the value of $name
.
But in a more real-world example the $name
variable will most likely be set based on a user input – and as such there can be several different values for it. However say we know for a fact what some of our values for the $name
variable are going to be Mike
, Eric
, JD
. We can utilize the if...elseif...else
statement to handle these different variations:
IF…ELSEIF…ELSE Statements
The above can be shortened further through the use of the PHP ternary operator – discussed at detail within this tutorial.
Now there is one remaining conditional statement within PHP called the switch
statement. The switch statement essentially acts as an alternative the if...elseif...else
statement when the condition for each statement is checking the same variable. This is covered in more detail within the next tutorial.