-3

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

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
  • Because in the second you're doing an OR of 'B' and 'C', then comparing the result of that with $var; 'B' OR 'C' will evaluate to a Boolean (true), so you get type casting $var to Boolean to compare with Boolean true – Mark Baker Feb 13 '14 at 07:55

2 Answers2

1

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

Alma Do
  • 37,009
  • 9
  • 76
  • 105
0

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

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

Diwakar upadhyay
  • 434
  • 5
  • 14