How to Use the Ternary Operators in PHP

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:


$number = 4;

if($number % 2 == 0){
    echo "The number is even";
} else {
    echo "The number is odd";

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:


$number = 4;

$number % 2 == 0 ? echo "The number is even" : echo "The number is odd";

In general, the format is:

test ? true statement : false statement


Want to Learn More?

Become a member and get access to the member only area of this site.



Your email address will not be published.

PHP for Beginners

Would you like lifetime access to the hugely successful PHP for Beginners course? Click here to find out how.

FREE Code Snippets

FREE hints and tips delivered direct to you once per month.