I wanted to do Fizzbuzz in php by using unary if, but the output is not what I expect, and I didn’t understood why, so I have copy-paste the code to 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
Ternary operator (which you called “unary if”) in javascript uses right associativity and the same operator in php uses left associativity.
Yes, this could be fixed with more parenthesis (as well as any problem relating operator precedence).