If you want to use the '||' operator to set a default value, like this:
<?php
$a = $fruit || 'apple'; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)'apple' == TRUE)
?>
instead, you have to use the '?:' operator:
<?php
$a = ($fruit ? $fruit : 'apple');//if $fruit evaluates to FALSE, then $a will be set to 'apple'
?>
But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
<?php
function fruit($confirm) {
if($confirm)
return 'banana';
}
$a = (fruit(1) ? fruit(1) : 'apple');//fruit() will be called twice!
?>
But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator» (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:
<?php
$a = ($fruit ? : 'apple'); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to 'apple'
?>
But remember that a non-empty string '0' evaluates to FALSE!
<?php
$fruit = '1';
$a = ($fruit ? : 'apple'); //this line will set $a to '1'
$fruit = '0';
$a = ($fruit ? : 'apple'); //this line will set $a to 'apple', not '0'!
?>