How to use PHP ternary operator for if...else condition

If else condition is used to execute the block of code based on condition. If the given condition is not true then alternative code of block will be executed.


if (condition) {
    // code to be executed if the given condition is true...
} else {
    // code to be executed if the given condition is false...

You can see the above condition takes 4 lines of code. So when you have only simple one line statement to be executed in if... else condition, then you use ternary operator.

Ternary operator(shorthand property) is same regular if...else condition in one line.


(condition) ? (statement to be executed for true condition) : (statement to be executed for false condition)



$x = 5;
$text = ($x < 10) ? 'variable is x is less than 10' : $text = 'variable x is greater than 10';

Or something like this:


$pass = true;
$result = ($pass) ? 'Passed' : 'Failed';

This is useful when assiging value to variable in form submit.

$first_name = isset($_POST['first_name']) ? $_POST['first_name'] : null;

The ternary operator reduces code be written and makes it more readable. Note that variable in conditional code should be already defined. Else it will give the error.  I hope you like this article.