Question

Below is the example:
If I write like:

<?php
$var = 'A';
echo    ($var == 'B' || $var == 'C')  ? 'B or C' : 'A';
?>

//Out will be "A" But if I write like below:

<?php
$var = 'A';
echo    ($var == ('B' || 'C'))  ? 'B or C' : 'A';
?>

It give me out put as "B or C".
Here ($var == ('B' || 'C')) is not correct or i am missing something?

Created PHP fiddle: http://phpfiddle.org/main/code/wju-46r

Was it helpful?

Solution

This has no relation to ternary operator. It's about type juggling and comparison.

In second case, you're doing 'B' || 'C' which will be treated as true - since || is logical operator. So 'A' == true is true because of type juggling, thus B or C will be your result

OTHER TIPS

echo ($var === ('B' || 'C')) ? 'B or C' : 'A';

This is the right answer you must have to check data type also.

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