Given the right configuration, a very simple process and enough memory, does PHP have a ceiling on number of iterations in loops, or would it just continue to execute until you either exhausted the memory, hit the max execution time, or faulted in some other way?
If so, is it different for the various types of loops? while, do...while, for, foreach?
For instance:
<?php
for ($i=0; $i<999999999999999999; $i++) {
echo "$i<br/>";
};
I realize this is a little absurd, but it's mostly a curiosity of mine about PHP limitations. I couldn't find anything in the docs or this specific question discussed here on SO.
I did run this script in a local development environment running PHP 7.1 built in server on a 3.1GHz Intel Core i7 MacBook Pro with 16GB RAM, with a max_execution_time
of zero. After about 720,000 the browser itself would reach it's own limitations and freeze up. I did run this same test via the CLI and while it took a really long time, it did execute and ran but I eventually manually stopped it.
There is no limit on the number of records that you can iterate using a For loop. This is restricted only by the size of collection that is being iterated (collection is so large that the system runs out of memory during processing). 200,000 for Synchronous Apex and 1,000,000 for Asynchronous Apex.
There are four different types of loops supported by PHP.
The major difference between for loop and while loop is that in the case of for loop the number of iterations is known whereas in the case of the while loop number of iterations is unknown and the statement will run until the condition is proved false.
PHP in TeluguThe 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed. For improved performance, the concept of references needs to be used.
tl;dr
PHP will gladly loop forever assuming it has enough resources and that the process isn't terminated by the operating system, Apache, user, etc...
You are confusing a browser issue with PHP. The browser cannot handle the rendering of so many echo "$i<br/>";
so it crashes or freezes or whatever. It's also possible that PHP is running out of memory by placing so many $i
into the output buffer before it sends it to the browser.
Try benchmarking the code properly and you will quickly get your answer:
// Let's set the start timer
$start = microtime(true);
// Add or remove 9's as you please
for($i=0; $i<999999999999999999; ++$i){}
// How many seconds did this take to complete?
echo (microtime(true) - $start).' seconds<br/>';
// What was the peak memory usage during this code execution?
echo memory_get_peak_usage(true).' bytes used';
Assuming Apache/PHP/your browser does not time out then you should see a result; if not then go command-line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With