3

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

2 Answers 2

7

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).

Sign up to request clarification or add additional context in comments.

1 Comment

also note the super cool 2 versions of logical "and" and "or" and their difference in precedence! (in PHP)
2
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.