Web Development & WordPress

Exploring Nested Ternary Operations in PHP

This guide demonstrates how to use braces to properly nest ternary operators in PHP, ensuring correct evaluation and avoiding common errors with practical example.

In Line 7 and 11 you can see how the first braces are used between the ternary operators which makes the output different.

<?php
$numberToCheck = 10;

//$output = ($numberToCheck %2 == 0 ) ? "Great" : ( $numberToCheck == 11 ) ? " Not Ok " : " Check Again";

//echo $output; // Error in Output
$output = ($numberToCheck %2 == 0 ) ? "Great" : ( ( $numberToCheck == 11 ) ? " Not Ok " : " Check Again");

echo $output;  
echo "<br>";
$output = (($numberToCheck %2 == 0 ) ? "Great" : ( $numberToCheck == 11 ) )? " Not Ok " : " Check Again";

echo $output;   
?>

OUTPUT:

Great
Not Ok

Leave a comment