How to Use the Ternary Operators in PHP

phplogo.jpg

In this lesson we will look at how we can shorten the IF THEN ELSE statement by using the ternary operators in PHP.

Consider the following IF, THEN, ELSE statement:

The above code will check if a number is even.  If even then we display the message "The number is even" else we display the message "The number is odd".

In this particular case, since we have assigned $number the value of 4, we will get the message "The number is even".

The code can be shortened a little by using ternary operators as follows:

In general, the format is: