CODING ACADEMY

View Original

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:

See this content in the original post

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:

See this content in the original post

In general, the format is:

See this content in the original post