Search code examples
phpfor-loop

Why does my PHP code doesn't work anymore for no reason?


I have a for loop in my code. I haven't changed anything on this part of code for about 5-6 days and I never had problems with it.

Since yesterday I tried to reload my code and it allways gives me this error:

Maximum execution time of 30 seconds exceeded - in LogController.php line 270

Well I can't explain why but maybe someone of you could look over it.

This is my code around line 270.

$topten_sites = [];
for ($i = 0; $i <= count($sites_array); $i++) {
    if ($i < 10) { // this is 270
        $topten_sites[] = $sites_array[$i];
    }
}
$topten_sites = collect($topten_sites)->sortByDesc('number')->all();

As I said, it worked perfectly, so why it gives me an error? If I uncomment these lines and every other line that contains the $topten_sites array, the code workes again.


Solution

  • This looks wrong:

        for ($i = 0; $i <= $sites_array; $i++) {
            if ($i < 10) { // this is 270
                $topten_sites[] = $sites_array[$i];
            }
        }
    

    If $sites_array is an array, it makes no sense to compare it to an integer so you probably have a never-ending loop.

    If you just need the first 10 elements in another array, you can replace your loop with:

    $topten_sites = array_slice($sites_array, 0, 10);