PHP Conditional Operators

In this lesson, you will learn about Conditional Operators in PHP, their usage, and examples to better understand the topic.


PHP Conditional Operators

One of the essential Operators in PHP is known as the conditional operator. It initially assesses an expression for a true or false value and formerly runs one of the two given statements depending upon the result of the evaluation.

The table below illustrates the Conditional Operators in PHP Programming Language:

Logical Operators Symbol Logical Operators’ Names Example
? : Conditional Expression ($a > $c ) ? $a :$c;

If the condition is true? then value a: Otherwise, value c

?? Null coalescing

{ This conditional operator was announced in PHP 7}

$x = $a ?? $c

If the value of $a is not null and exists, then the operator returns the value of $a; otherwise, $c.

Example

<?PHP
echo "PHP Arithmetical Operator Example";
echo "<br>";
echo "  ---------------------------------------- ";
echo "<br>";
$a = 84;
$c = 85;
echo '$a  = ', $a, "<br>", '$c  = ', $c;
echo "<br>";
$var_result = ($a > $c) ? $a : $c;

echo " Conditional Expression-> ", '? :';
echo "<br>";
echo "Expression -> ", 'result= ($a > $c ) ? $a :$c';
echo "<br>";
echo "Assign ", '$a', " to result if condition is true to result else ", '$c';
echo "<br>";
echo "Result -> ", $var_result;
echo "<br>";

echo "<br>";
$var_result = ($a < $c) ? $a : $c;

echo " Conditional Expression-> ", '? :';
echo "<br>";
echo "Expression -> ", 'result= ($a < $c ) ? $a :$c';
echo "<br>";
echo " Assign ", '$a', " to result if condition is true to result else ", '$c';
echo "<br>";
echo "Result -> ", $var_result;
echo "<br>";
?>

Output

PHP Arithmetical Operator Example
---------------------------------------- 
$a = 84
$c = 85
Conditional Expression-> ? :
Expression -> result= ($a > $c ) ? $a :$c
Assign $a to result if condition is true else $c
Result -> 85

Conditional Expression-> ? :
Expression -> result= ($a < $c ) ? $a :$c
Assign $a to result if condition is true else $c
Result -> 84

Null coalescing Example

<?PHP
echo "PHP Null coalescing Example";
echo "<br>";
echo " ---------------------------------------- ";
echo "<br>";

$vehicle1 = "Use Train !!";
// variable $vehicle is the value of $_GET['vehicle']
// and 'Public Transport' will be dispalyed if $_GET['vehicle'] does not exist
echo $vehicle = $_GET["vehicle"] ? ? "Public Transport";
echo "<br>";

// Above variable $vehicle is 'Use train' if $vehicle exist or not null
echo $vehicle = $vehicle1 ? ? "Use bus";
?>

Output

PHP Null coalescing Example
----------------------------------------
Public Transport
Use Train !!

This concludes the PHP Conditional Operators lesson. In the next lesson, you will learn about another type of Operator in PHP: the String Operator.