PHP Ternary Operator & Nested Ternary Operator

Share Now

//normal
$n = 12;
$ns = 12;
if( 12 == $n ){
    echo "Twelve";
}else if( 10 == $n ){
    echo "Ten";
} else {
    echo "Just a number";
}

echo "\n";

$numberInWord = (12 == $n ) ? "Twelve" : "Just a number";
$numberInWordNested = ( 12 == $ns ) ? "Twelve" : ( 10 == $ns ) ? "Ten" : "Just a number";
echo $numberInWord;
echo "\n";
echo $numberInWordNested;

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert