Reputation:
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.
Upvotes: 0
Views: 114
Reputation: 20860
Put else condition part in parenthesis :
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
Refer operator precedence
Upvotes: 0
Reputation: 11310
Here it is :
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
?>
Upvotes: 0
Reputation: 68536
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..
}
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
}
Upvotes: 2
Reputation: 13738
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
Upvotes: 0
Reputation: 7438
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));
Upvotes: 0
Reputation: 33542
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.
?>
Upvotes: 3
Reputation: 28753
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.
Upvotes: 0