如何检查是否是第一次在 foreach 迭代中的 if 语句中找到值 [英] How to check if it is the first time a value is found in if statement inside a foreach iteration

查看:41
本文介绍了如何检查是否是第一次在 foreach 迭代中的 if 语句中找到值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组.

$array1 = array('John','Mike','Tim','Dan');

使用 foreach 迭代,我循环通过 $array1,执行返回 truefalse 的 db 查询 所以我有:

Using a foreach iteration, I'm looping through $array1, performing a db query that returns either true or false so I have:

foreach ($array1 as $key => $value) {
    $dbQueryResult = true; // or false depending on iteration
    if($dbQueryResult === true){
        // HOW DO I CHECK IF IT IS THE FIRST TIME I'M GETTING HERE
    }
}

我如何检查这是否是我第一次在 foreach 迭代中的 if 语句中获得所需的结果,如上例所示?

How do I check if it's the first time I'm getting a desired result in an if statement inside a foreach iteration like in the above example?

推荐答案

使用变量来保存该信息

$firstTime = true;

foreach ($array1 as $key => $value) {
    $dbQueryResult = true; // or false depending on iteration
    if($dbQueryResult === true){
        // HOW DO I CHECK IF IT IS THE FIRST TIME I'M GETTING HERE
        if ( $firstTime ) {
            // do first time stuff

            $firstTime = FALSE;
        }

    }
}

这篇关于如何检查是否是第一次在 foreach 迭代中的 if 语句中找到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆