How to use the PHP Ternary Operator

  601 views   7 months ago PHP

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.

Syntax:

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.

Syntax:

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

Example:

<?php

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

Or something like this:

<?php

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

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]