Ternary operator in javascript and PHP, different output

I wanted to do Fizzbuzz in php using a unary if, but the result is not what I expect and I didn’t understand why, so I will copy the code in javascript and now the result is as expected. Why?

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(function(){
papa ='Javascript Output: ';
for($i=1;$i <= 10; $i++){
papa += ($i %5 === 0 && $i %3 === 0) ? 'FizzBuzz' : ($i % 3 === 0) ? 'Fizz' : ($i % 5 === 0) ? 'Buzz' : $i;
$('#result').text(papa);
}
})
</script>
<?php
echo 'PHP Output: ';
for($i=1;$i <= 10; $i++){
$papa ($i %5 === 0 && $i %3 === 0) ? 'FizzBuzz' : ($i % 3 === 0) ? 'Fizz' : ($i % 5 === 0) ? 'Buzz' : $i;
echo $papa;
}
?>
<div id='result'></div>

      

Output

PHP Output: 12Buzz4BuzzBuzz78BuzzBuzz
Javascript Output: 12Fizz4BuzzFizz78FizzBuzz

      

+3


source to share


2 answers


The ternary operator (which you called "unary if") in javascript uses right associativity, and the same operator in php uses left associativity.



Yes it can be fixed with a lot of parentheses (as well as any operator precedence issue).

+5


source


in PHP, change 
    ($i %5 === 0 && $i %3 === 0) ? 'FizzBuzz' : ($i % 3 === 0) ? 'Fizz' : ($i % 5 === 0) ? 'Buzz' : $i;
    to:
    ($i %5 === 0 && $i %3 === 0) ? 'FizzBuzz' : ($i % 3 === 0) ? 'Fizz' : (($i % 5 === 0) ? 'Buzz' : $i);

      



+2


source







All Articles