3

I've recently programmed a lot in javascript and I was trying to use some shorthands in PHP.

Consider this statement:

$value = 1;

return $value == 1 ?
    'a' : $value == 2 ? 'b' : 'c';

Could anyone explain me why this returns 'a' in jQuery and 'b' in php?

clod986
  • 2,527
  • 6
  • 28
  • 52

3 Answers3

9

In PHP, the ternary operator is left-associative (or from the manual, a little less clear).

this is because ternary expressions are evaluated from left to right

In Javascript, the ternary operator is right-associative.

note: the conditional operator is right associative

So, in PHP your code executes like this:

($value == 1 ?
    'a' : $value == 2) ? 'b' : 'c';

And in Javascript, it executes like this:

value == 1 ?
    'a' : (value == 2 ? 'b' : 'c');

So, to get the same results, you need to tell either one to act like the other:

echo $value == 1 ?
    'a' : ($value == 2 ? 'b' : 'c');

This is (one of the?) the reason why nested ternary operators are a bad idea. They're not readable and prone to these kind of mistakes!

ishegg
  • 9,685
  • 3
  • 16
  • 31
1

You need to wrap the "else" part of the condition in parantheses

$value = 1;

echo $value == 1 ? 'a' : ($value == 2 ? 'b' : 'c');

This would return 'a' in php

Manav
  • 1,357
  • 10
  • 17
1

Use parenthesis do define the correct order of evaluation :

$value == 1 ? 'a' : ($value == 2 ? 'b' : 'c')
Julien Lachal
  • 1,101
  • 14
  • 23