0

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.

2
  • Have you already fetched all the results of the query at the point you're trying to do this? Commented Aug 10, 2016 at 17:31
  • Yes, I have fetched the results at this point. I have contemplated putting them into an array however I'm not sure how to integrate this into the loop. Commented Aug 10, 2016 at 17:33

3 Answers 3

3

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 : https://stackoverflow.com/a/38880057/3799829

Sign up to request clarification or add additional context in comments.

1 Comment

This covers exactly what I need. Thank you.
3

If your query results are returned as an array you can use if(in_array($i, $results)) to do a check of $i against the results

Comments

2

Add your values into an array while you fetch your query results. I used PDO here for example, but you should be able to adapt it to whichever database extension you're using:

while ($row = $stmt->fetchObject()) {
    $exclude[$row->value] = true;
    // whatever else you're doing with the query results
}

If you use the values as keys in the array of things you want to skip, checking for them in your for loop should be more efficient than using in_array.

for($i = 1; $i <= $num_rows; $i++) {
    if (isset($exclude[$i])) continue;
    // rest of loop

2 Comments

Nicest of the answers here, no useless loops
@Bob0t I appreciate the compliment and the reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.