How to check if it is the first time a value is fo

2020-04-19 08:40发布

问题:

Suppose I have an array.

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

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
    }
}

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?

回答1:

Use a variable to keep that information in

$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;
        }

    }
}