Skip to content Skip to sidebar Skip to footer

Javascript-like || In Php

In javascript, I can use, for example such statement: window.foo = window.foo || []; If there's no window.foo it will be assigned to array, but won't be converted into boolean. B

Solution 1:

The difference is in what the operators return. In PHP, the logical operators return boolean values. In JavaScript, the logical operators return the actual operands and rely on implicit conversions to turn them into booleans when the context requires it.

If you want the functionality of returning the first operand if it evaluates to TRUE and the last otherwise in PHP, you can use the short-hand form of the ternary operator (?:):

PHP.net says:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Post a Comment for "Javascript-like || In Php"