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:

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

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top