I don't really understand the following expression, what it does and how it works.
a || b = c
I guess it check if a is true, and if it's not, it run b = c?
Exemple of application:
$id || $data['created'] = $now
It's short for:
($id == true) || (($data['created'] = $now) == true)
Factoring in short circuit logic and the fact that the result of the expression itself is ignored:
if (!$id) {
$data['created'] = $now;
}
See also: Logical operators
In my understanding it means:
a OR the posibility to give b the value of c.
or in your case
$id
OR the posibility to give $data['created']
the value of $now
|| means OR, thus a == true OR (b = c) == true. This latter is strange, because you should not use '=' in an if statement.
An working example is:
$a = false;
$b = 19;
if ($a == true || $b == 19)
{
// continue here.
}
Although $a is false, the if-statement looks at the second part and that statement is true. Thus the statement can continue.
It's a short-circuit expression. In general, that means the expression will be evaluated just to the point where the whole result is found. Thus a || b
will not evaluate b, if a
is true (because true or false, won't change the total outcome) and similar to that a && b
will not evaluate b
if a
equals to false.
Now to your example:
If a
equals to true
, no need to evaluate the second operand b=c
and c will not be assigned to b.
If a
equals to false
then second operand will be evaluated, first assigning c to b and then returning the result as the result of this expression.
There are many way to write this expression. I like using the Ternary Operator, it's the same thing: a ? a : b=c
$a=0;
$c=1;
($a) ? $a : $b=$c;
echo $b;
or
$data['created'] = ($id) ? $id : $now;
your code is using a comparison operator || is OR in a short-circuit expression. you can use ?: like my examples or just:
switch(true) {
case $a : $a; break;
default : $b=$c; break;
}
That can also be expressed with a list of IF ELSEIF ELSE. Short-circuit expression's, Ternary Operator expression's and switch are cleaner and imo faster than list's of IF statements.
Yes, you are right.
But here is an important part from the manual that you should heed:
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Example #2 Undefined order of evaluation
$a = 1;
echo $a + $a++; // may print either 2 or 3
$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
Note:
Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.