I don't seem to be able to assign multiple variables in an "if"
statement. The following code:
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if ($result1 = a(1) && $result2 = b(1))
{
echo $result1 . ' ' . $result2;
}
?>
Returns "1 bar" rather than "foo bar". If I remove the second condition/assignment it returns "foo".
Is there a way to assign multiple variables in an "if" statement or are we limited to just one?
This is all about operator precedence
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
?>
https://repl.it/IQcU
UPDATE
assignment operator =
is right-asscoiative, that means, evaluation of operand on rhs has precedence over the lhs operand.
thus,
$result1 = a(1) && $result2 = b(1)
is equivalent of,
$result1 = (a(1) && $result2 = b(1))
which evaluates
$result1 = ("foo" && [other valild assignment] )
which will result that,
$result1
becomes true
and echo true
/string value of boolean true (strval(true)
) outputs/is 1
you can also check that revision, https://repl.it/IQcU/1
to see that below statement
$result1 = a(1) && $result2 = b(1)
is equivalent of this one.
$result1 = (a(1) && $result2 = b(1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With