douniani679741 2016-06-13 21:37
浏览 37
已采纳

为什么这个PHP代码不起作用,我该如何纠正呢?

hello i am getting familiar with PHP and i am wondering why this code doesn't work and is there an alternative way to make it work i.e: which other way can this be accomplished.

<?php
`$`fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset(`$`fruit);
foreach(`$`fruit as `$`key => `$`val){
if((`$`key=="a" && `$`val=="apple" ) && (`$`key=="b" && `$`val=="banana") ){
echo "apple and banana";
}
}
?>
  • 写回答

2条回答 默认 最新

  • drvonr6573 2016-06-13 22:01
    关注

    Try this

    <?php
    $fruit = array('a' => "apple", 'b' => "banana", 'c' => "cranberry");
    
    reset($fruit);
    foreach($fruit as $key => $val)
    {
        if(($key=='a' && $val=="apple" ) || ($key=='b' && $val=="banana") )
        {
            echo "apple and banana";
        }
    }
    ?>
    

    As the others have mentioned, when you write PHP you are not supposed to surround the sigit ($) with quotes.

    Other then fixing that issue, I noticed another issue. When you are looping through the array, the $key variable can only deal with one element at a time. In order for your programs if condition to be true, you required $key variable to have two values at the same time:

    if(($key=="a" && $val=="apple" ) && ($key=="b" && $val=="banana"))
    

    Notice the &&. You are saying that $key has to be equal to "a" and to "b" at the same time. $val also has to be equal to "apple" and "banana" at the same time. This condition is impossible.

    Think of it this way. A variable is your hand. Your hand can only hold one thing at a time. $key is your left hand, and $val is your right. If I tell you that you can only enter my room if you are holding two things in your left hand and two things in your right hand, you will say to me, that is impossible! I can only hold one thing in my left hand, and only one thing in my right hand. This is a silly analogy but maybe it will help.

    Anyway, that is why I changed the && to an ||. In my code you may notice how I changed the array identifier (a, b, c) from being surrounded in single quotes to double quotes. This is just my style. I like to do that.

    Anyway, I hope this helps. Sorry if there are any spelling mistakes, I am in a rush and have to go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证