0

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.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126

7 Answers7

3

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.
?>
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
2

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
}
Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

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.

GautamD31
  • 28,552
  • 10
  • 64
  • 85
0
<?php

$id = "a";

echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));
falinsky
  • 7,229
  • 3
  • 32
  • 56
0

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

Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

Here it is :

<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
?>
Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
0

Put else condition part in parenthesis :

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

Refer operator precedence

Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101