简体   繁体   中英

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.

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);

Why would You iterate entire array if You only want first 10 results?

    for ($i = 0; $i < 10; $i++) {
            $topten_sites[] = $sites_array[$i];
    }

To answer the actual answer; code never stops working "for no reason". Code works or it doesn't, both for a reason. If it stops working changed compared to your previous tests. 变化。 "Sometimes it works, sometimes it doesn't" falls in the same logic. Code will always behave exactly the same every time, just some of the parameters have changed, you have to find which one.

In your case, i'm guessing the entries in your array have increased. PHP and arrays aren't best friends when it comes to speed, arrays are slow. It could very well be that your array was smaller when you tested it (wasn't probally the fastest to begin with), but now with the current amount it just hit the threshold of 30 seconds.

It could also be that a part of code before this bit of code takes a lot of time (say suddenly 28 seconds instead of 20), and your loop (which never changed) does it's job in the regular 3seconds it always does, now runs into problems

Use it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM