PHP:在if语句中分配多个变量

问题描述:

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?

我似乎无法在中分配多个变量“if” code> 声明。 以下代码: p>

 &lt;?php 
 
function a($ var)
 {
 if if($ var == 1)
 {
返回 'foo'; 
} 
 
返回false; 
} 
 
函数b($ var)
 {
 if if($ var == 1)
 {
返回'bar'; \  n} 
 
返回false; 
} 
 
if($ result1 = a(1)&amp;&amp; $ result2 = b(1))
 {
 echo $ result1。  ''。  $ result2; 
} 
 
?&gt; 
  code>  pre> 
 
 

返回“1 bar”而不是“foo bar”。 如果我删除了第二个条件/赋值,则返回“foo”。 p>

有没有办法在“if”语句中分配多个变量,还是仅限于一个? p > div>

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,

$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:-

Why 1 bar is coming through OP's code

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';
}
?>