Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Assign multiple variables in if statement

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?

like image 412
Bob Meador Avatar asked Dec 23 '22 17:12

Bob Meador


1 Answers

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)) 
like image 116
marmeladze Avatar answered Jan 17 '23 11:01

marmeladze