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条)

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴