douzhongjiu2263 2016-06-10 18:19
浏览 70
已采纳

如何跟踪变量值是否在同一个php while循环中多次使用

I found this snippet in a different question and answer, and it detects if a variable value is the same as the variable value in the previous loop.

$prevValue = NULL;
while(condition) {
 if ($curValue == $prevValue) {
  //do stuff
 }
 $prevValue = $curValue;
}

However what I want to do is to check if a variable value has been used before in the loop, but anywhere in the loop, so if the value happened 1 or 2 or 10 loops ago I want it to tell me if the variable value has come through the loop before.

  • 写回答

3条回答 默认 最新

  • douchun6221 2016-06-10 18:22
    关注

    Use an array to store each value and then check if the current value is in the array:

    $prevValues = array();
    while(/*condition*/) {
        if (in_array($curValue, $prevValues)) {
            //do stuff
        }
        $prevValues[] = $curValue;
    }
    

    As Marc B points out in a comment, you can do it this way as well. It might be marginally faster but I haven't tested it:

    while(/*condition*/) {
        if (isset($prevValues[$curValue])) {
            //do stuff
        }
        $prevValues[$curValue] = 1;  //set to whatever
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵