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:

<?php

$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:

<?php

$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 here.

Comments

Your email address will not be published.

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.