In php, how do logical operators work _with non-booleans_?
-
16-09-2019 - |
Question
In other programming languages (Python, Ruby, Scheme), I'm used to doing things like
$foo = $cat && $dog;
$bar = $fruit || $vegetable;
I would expect that $foo would get assigned to $dog if $cat were null, and $bar to $fruit if $fruit were NOT null. I seem to recall getting burned for doing things like this in PHP, and I've never learned exactly how logical operators handle non-boolean operands. Can someone explain or point me in the right direction? I tried reading the following page in the official docs, but it doesn't deal with non-booleans:
Solution
In PHP the result of a boolean comparison is always a boolean, the operands are coerced to boolean.
http://us3.php.net/manual/en/language.types.boolean.php
explains which values, when they are coerced, will becomes true or false.
OTHER TIPS
Would this work for you?
$foo = $cat ? $cat : $dog;
The first $cat will get turned into a Boolean based on known rules. If it's true then $foo will be $cat otherwise it's $dog.