PHP中的foreach数量有限吗?

I don't know is it right or not. I have a PHP file with contents like this:

$x = explode("
", $y); // Making $x has length 65000
foreach ($x as $k) {
    //Some code here
}

And often my script auto-stopping after ~25000 loops. Why? Is it PHP default configuration?

This behaviour can be because of 2 reasons

  1. The script execution time is more than allocated to it ... Try increasing max_execution_time in php.ini .

  2. The memory limit of script may be more than allocated .For this try changing the value of memory_limit in php.ini

The default memory limit of PHP is 8MB (I mean standard distro's, not a default PHP compile from source, because that is limitless).

When I do this code:

$x = array();

for ($i = 0; $i < 65000; $i++) {
    $x[$i] = $i;
}


echo (memory_get_peak_usage()/1024).'<br />';
echo (memory_get_usage()/1024).'<br />';
echo count($x);

It outputs:

9421.9375
9415.875
65000

To test this, I've increased my memory limit tho. But it would abort with an error if you can't allocate more memory;

for ($i = 0; $i < 1e6; $i++) { // 1 Million
    $x[$i] = $i;
}

It reports back;

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 32 bytes) in /Applications/MAMP/htdocs/run_app.php on line 5

For personal use (I have 16GB RAM, so it's no issue) I use these starting codes:

// Settings
ini_set('error_reporting', E_ALL); // Shows all feedback from the parser for debugging
ini_set('max_execution_time', 0); // Changes the 30 seconds parser exit to infinite
ini_set('memory_limit', '2048M'); // Sets the memory that may be used to 512MegaBytes

This way you can increase your limit the way you want it. This won't work with online hosts unless you have a dedicated server tho. This is VERY dangerous tho, if you don't know what you're doing. Infinite loops will crash your browser or even your OS if it starts to lack RAM/resources.

In the foreach loop, pass the array as a reference. In PHP, foreach makes a copy of the array before it begins looping. Thus if you have an array that is 100K then foreach will allocate at the very least another 100K for processing. By passing it as a reference, you are only concern about the size of an address.