leoarce leoarce - 5 months ago 11
PHP Question

How to track if a variable value is used multiple times in same php while loop

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.

Answer

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