Often in PHP, I see:
$result = mysql_query($query) or die();
Coming from python, I know why this should work, because or returns the first value if it is true in a boolean context, and the second value otherwise (see this).
But when I try the above technique in PHP in another context, for example something like:
$name = "John Doe";
echo $name or "Anonymous";
The or doesn’t return the first value (“John Doe”), it returns 1.
Why does this work in the mysql_query() result case, but not in other cases? Is it bad to use in a mysql_query() case (ignore the fact that I am not returning a useful error to the user)?
In PHP, variable assignment (the equals sign) and functions both take precedence over the
oroperator. That means a function gets executed first, then the return value of the function is used in theorcomparison. In turn when you use two values/variables together with anoroperator, it compares the two values first then returns a Boolean value.Therefore, the order of evaluation in this example is:
mysql_query($query)Returns either a result set for DQL queries such as
SELECT, or a Boolean value for DDL, DML or DCL queries such asCREATE,DROP,INSERT,UPDATE,DELETEandALTER.$result = mysql_query($query)The result of this query execution is assigned to the variable
$result.$result /* = ... */ or die();If it’s either a result set or
true, it’s considered true (aka “truthy”) so theorcondition is satisfied and the statement ends here. Otherwise the script woulddie()instead.echois a language construct and therefore doesn’t actually return a value, so it doesn’t run like a function before theorcomparison is made.As
$name or "Anonymous"is always true because the string"Anonymous"is non-empty and therefore truthy, theechoimplicitly convertstrueto1, hence that output.The order of evaluation in this example is:
$name = "John Doe";Pretty straightforward — assigns the string John Doe to
$name.$name or "Anonymous"PHP discovers that
$namecontains the string John Doe, so what ends up being evaluated is the following:"John Doe" or "Anonymous"Since at least one string is non-empty here, it’s considered truthy and the condition is satisfied. This evaluation then returns
true.echo true /* $name or... */;Converts
trueto1and prints the number 1.