Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php one_liner if compared to javascript

Tags:

javascript

php

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?

like image 422
clod986 Avatar asked Nov 20 '25 09:11

clod986


2 Answers

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!

like image 104
ishegg Avatar answered Nov 23 '25 00:11

ishegg


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

like image 24
Manav Avatar answered Nov 22 '25 23:11

Manav