Question

I'm using this below example code:

<?php
$id = "a";
echo $id == "a" ? "Apple" : $id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others";

I want to get output as Apple. But i got Dog. Any one can please help me.

Was it helpful?

Solution 3

<?php

$id = "a";

echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));

OTHER TIPS

From the notes on ternary operators: http://www.php.net/manual/en/language.operators.comparison.php

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Way #1

Use a switch instead and it also helps your code more readable..

switch($id)
{
    case "a":
        echo "Apple";
        break;
    
    case "b":
        echo "Bat";
        break;
    
    //Your code...
    
    //More code..
}

Way #2

You can also make use of array_key_exists()

$id = "a";
$arr = ["a"=>"Apple","b"=>"Bat"];
if(array_key_exists($id,$arr))
{
    echo $arr[$id]; //"prints" Apple
}

Try like

echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");

If the condition will false then only the remaining block that I have put within () will execute.

try to make separate your conditions

echo ($id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others"));

else use switch() would be better

Here it is :

<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
?>

Put else condition part in parenthesis :

echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");

Refer operator precedence

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top