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

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?