duanhuang1967 2012-10-06 17:31
浏览 14
已采纳

如何检查列表中的一个var? 而不在列表中

I have the following array.

$ar = array("apple:3","banana:2","canopule:6","grapes:5","cherry:8");

How can I check to see if the following variable

$a = "grapes";

Is in the array (in this case grapes:5) and if it is, return the matched string. I.e., "grapes : 5"

If it's not in the list (e.g., matching "strawberry"), return "strawberry : not found."

I have this:

for($i = 0; $i < count($ar); $i++) {
    list($name,$count)=explode(":",$ar[$i]);
    if($a==$name)
        echo "$a : $count";
    else
        echo "$a : not found!";
}

If it matches, it works fine. But if not, I get

strawberry : not found!strawberry : not found!strawberry : not found!strawberry : not found!strawberry : not found!

It returns every false case instead of just one.

  • 写回答

3条回答 默认 最新

  • douzui6173 2012-10-06 17:35
    关注

    Try like this:

    $ar=array("apple:3","banana:2","canopule:6","grapes:5","cherry:8");
    $a = "strawberry";
    $result = '';
    for($i=0;$i<count($ar);$i++){
        list($name,$count)=explode(":",$ar[$i]);
        if($a == $name){
            $result = "$a : $count";
            break;
        }
    }
    
    if($result){
        echo $result;
    } else {
        echo $a." : Not found";
    }
    

    Simply check if there is something in loop if yes print result, if no add not found.

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

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图