Why is my PHP code no longer working for no reason?

I have a for loop in my code. I did not change anything in this part of the code for 5-6 days, and I never had a problem with this.

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

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

Well, I can’t explain why, but maybe one of you could check it out.

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

Like I said, it worked perfectly, so why does this give me an error? If I uncomment these lines and every other line containing the $ topten_sites array, the code works again.

+5
source share
4 answers

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, there is no point in comparing it with an integer, so you probably have an infinite loop.

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

 $topten_sites = array_slice($sites_array, 0, 10); 
+15
source

Why would you repeat the entire array if you only need the first 10 results?

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

To answer the actual answer; the code never stops working "for no reason." The code works or not, for a reason. If it stops working with something compared to your previous tests. “Sometimes it works, sometimes it doesn't“ fall on one logic. ”The code will always behave the same every time, only some of the parameters have changed, you need to find which one.

In your case, I assume that the entries in your array have increased. PHP and arrays are not best friends, when it comes to speed, arrays are slow. It is possible that your array was smaller if you tested it (it was probably not the fastest to start with), but now with the current value it just reached a threshold of 30 seconds.

It may also be that part of the 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 the work in the usual 3 seconds, it always does, now it encounters problems

+1
source

Use it as follows:

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

Source: https://habr.com/ru/post/1241580/


All Articles