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;
}
?>
UPDATE
assignment operator =
is right-asscoiative, that means,
$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))
Need to add parentheses()
in each assignment like below:-
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
Output:- https://eval.in/804770
Correct explanation is given by @marmeladze here:-
The last if statements need some brackets, it should have been:
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
This ensures that things in the bracket are executed first and it will help.
You have to add ==
to check a condition.
Try this,
if ($result1 == a(1) && $result2 == b(1))
{
echo $result1 . ' ' . $result2;
}
Checked with belo example
<?php
function a ($var)
{
if ($var == 1)
{
return 1;
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 2;
}
return false;
}
if (1 == a(1) && 2 == b(1))
{
echo 'success';
}
?>