PHP - loops and rusources forach

I use the foreach loop to process a large set of elements, unfortunately it uses a lot of memory. (probably because it makes a copy of the array). There seems to be a way to save some memory with the following code: $items = &$array;

Isn't it better to use for loops?

And is there any way to destroy every element as soon as they are processed in the foreach loop.

eg.

  $items = &$array; foreach($items as $item) { dosomethingwithmy($item); destroy($item); } 

I'm just looking for the best way to handle a large number of elements without running out of resources.

+4
source share
4 answers

Try a for loop:

 $keys = array_keys($array); for ($i=0, $n=count($keys); $i<$n; ++$i) { $item = &$array[$keys[$i]]; dosomethingwithmy($item); destroy($item); } 
+6
source

In terms of resources, your code will be more efficient if you use a for loop rather than a foreach loop. Each iteration of your foreach loop will copy the current element in memory, which will take time and memory. Using and accessing the current item with an index is slightly better and faster.

+4
source

use this:

 reset($array); while(list($key_d, $val_d) = each($array)){ } 

because foreach creates a copy

+1
source

If you get this large data set from a database, it can often help try and use the data set as soon as it comes from the database. For example, from php documentation mysql_fetch_array .

 $resource = mysql_query("query"); while ($row = mysql_fetch_array($resource, MYSQL_NUM)) { process($row); } 

this loop will not create a copy in memory of the entire data set (at least not redundantly). A friend of mine accelerated some of her query processing 10 times using this technique (her datasets are biological, so they can become quite large). A.

+1
source

All Articles