dpfz27768 2015-02-20 00:21
浏览 37
已采纳

比较变量start和数组键

There is this array:

$array1 = array(51=>1.1, 45=>68, 57=>43, 62=>35, 74=>24);

And I want to verify if the value that is taken from the variable starts with any of the keys from the array. (the variable is passing correctly, I checked that)

foreach (array_keys($array1) as $key1) {
    if(preg_match("/^[$rvalue]/", $key1))
    {
        $positive1=true; 
        $fvalue1=$array1[$key1];
    }
    else{
        $positive1=false;
        }
}

The problem is that it runs all the array and always gives me the value of the last key, instead of one matching the variable. I'm new with regex, so might be that, don't know. Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • draxu26480 2015-02-20 01:41
    关注

    Seems kind of complicated for a simple task. How about at direct comparison:

    foreach ($array1 as $key1 => $value) {
        if (substr($rvalue, 0, strlen($key1)) == $key1)
        {
            $fvalue1 = $value;
            break;
        }
    }
    

    Just break from the loop when you find a match.

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

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)