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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了