views:

109

answers:

3

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:

http://us3.php.net/manual/en/language.operators.logical.php

+4  A: 

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.

tialaramex
allyourcode
I believe this is an accurate characterisation, but I have not tested it extensively so I can't promise there aren't any kinks.
tialaramex
Where does it say that logical operation expressions always evaluate to a boolean?
allyourcode
A: 

deleted cos I'm wrong!!!

David Archer
not quite, as I explained in my edited answer, there are some surprising rules about how operands are coerced to boolean. If $dog is "" or "0" then it is false, but if it is "Hello" or even "False" then it is true.
tialaramex
yeah thanks, I followed the link and see you're right :-)
David Archer
+1  A: 

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.

Jason
Yeah, but that's ugly.
allyourcode