PHP Foreach Loop

What is the impact on memory usage of using foreach instead of for in PHP? Well, I did a small test.

The test shows that only when you change the array within the loop, the array is copied for real. This can be illustrated with :

1
2
3
4
5
6
7
8
9
$array = array_fill(0, 100000, 'foobar');
echo 'Memory usage : ' . memory_get_usage() . ' bytes '. PHP_EOL;
 
foreach ($array as $key => $value) {
    echo 'Memory usage : ' . memory_get_usage() . ' bytes '. PHP_EOL;
    $array[1] = 'barfoo';
    echo 'Memory usage : ' . memory_get_usage() . ' bytes '. PHP_EOL;
    break;
}

The output of this piece of code is :

1
2
3
Memory usage : 5385920 bytes 
Memory usage : 5386072 bytes 
Memory usage : 10710480 bytes

Leave a Reply

Your email address will not be published. Required fields are marked *