Floyd Floyd - 3 months ago 12
MySQL Question

PHP skip for loop Iteration based on a query result set

Lets say for example I have a result set from a MySQL query that has produced values: 3,5,10,11 and so forth...

I would like to iterate through a for loop in PHP but exclude the any iteration that would equal any number in results of my MySQL query.

As it stands I currently have:

for($i = 1; $i <= $num_rows; $i++)
{
if($i == 3 or $i == 5)
{
continue;
}
//Rest of loop...


As you will all appreciate hard coding these values is very time consuming and not very efficient. If any one could help it would be greatly appreciated.

Answer

If you can gather automatically those values you are currently hard coding, you can use in_array($search, $array[, $strict])

Like this :

$bypass = array(3, 5);

for($i = 1; $i <= $num_rows; $i++)
{
    if( in_array($i, $bypass) )
    {
        continue;
    }

    // rest of the loop
}

PS : I prefer much more the "Dont Panic" answer, which doesn't use too many loops. (in_array will loop through the array to find your value). See his answer : http://stackoverflow.com/a/38880057/3799829