1

I am not sure what is happening with this code snippet.

<?php
$statementA = true;
$statementB = true;
$statementC = false;
echo $statementA ? $statementB ? "B IS TRUE" : "B IS FALSE" : $statementC ? "C IS TRUE" : "C IS FALSE";

Because statementA and statementB are both true I'd imagine the result would output B IS TRUE. For some reason it outputs C IS TRUE which is wrong because C is actually false. Regardless to what bool values you make the statements it will still output C IS TRUE.

If I change the echo line to be

echo $statementA ? $statementB ? "B IS TRUE" : "B IS FALSE" : ($statementC ? "C IS TRUE" : "C IS FALSE");

then everything will work correctly.

Aside from doing this properly by wrapping parentheses for readability sake (or using larger if/elseif blocks), why would this be outputting what its outputting?

Tested in php 7.3 and 5.6.

We re-ran this in C# and javascript and it works as expected.

Brad Moore
  • 316
  • 5
  • 23

0 Answers0