2

I'm trying to write a short script that will query my mysql db, and according to the amount of results (dynamic) i want the script on each segment.

For example, $arr is a result of a mysql_fetch_array and it has 872 items, I want to run my function 9 times, 1 for each 100 items and the last one for 72 items.

How can I do that?

1
  • Do you want each segment you loop over to be a maximum of 100 items? Commented Jun 25, 2011 at 17:07

2 Answers 2

3

Simply use a for loop with an incrementor that increments by 100. You can use array_slice() to get the concerned rows on each loop.

$dbRows = resultsFromDB();

for($i = 0; $i < count($dbRows); $i+=100) {
  $concernedRows = array_slice($dbRows, $i, 100);

  mySuperFunction($concernedRows);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Placing count() function in for condition slows down the execution, because it counts the items every loop pass.
@Ondřej Mirtes: No it doesn't. count() doesn't loop through the elements to count, it simply accesses a property of the zend_hash. I invite you to browse around the PHP source; specifically at zend_hash_num_elements() and PHP_FUNCTION(count). The number of items in an PHP Array (Zend Hash) is automatically updated on insertion/deletion. An array with 1,000,000 elements takes as long as an empty array to count.
@Ondřej Mirtes: He's wrong. Try it out yourself and check the PHP source. Any contributor will tell you that the only overhead of calling count() versus storing the result in a variable is the function call. That's it. O(1).
2

Maybe something like:

$length = count($arr);

for ($i = 0; $i < ceil($length / 100); $i++) {

}

If I understood.

3 Comments

For some reason, the loop runs only 108 times ($i = 108 after the loop ends) and count($arr) = 2700
@Or W: "only"? By your specification, an array of 2700 items should only run your function 27 times, not 108 times.
@Or W, maybe show the rest of the code you implemented it in. Try running $length = 2700; echo ceil($length / 100);. Should output 27

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.