doubi7496 2017-05-25 04:32 采纳率: 0%
浏览 76
已采纳

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?

  • 写回答

4条回答 默认 最新

  • dousao9569 2017-05-25 04:35
    关注

    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)) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真