Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

for-loop

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.

like image 692
ItzMe42 Avatar asked Jan 27 '16 09:01

ItzMe42


People also ask

Why is my PHP code not working?

If you are running your PHP script on a Windows computer, you need to manually install PHP. If you haven't already done so, your PHP code won't execute. Instructions for the installation process, versions and the system requirements are listed at the PHP website.

Why can't I use PHP in HTML?

The first thing to know is that, by default, you can't use PHP in HTML files, meaning files that end with . html . It's possible to configure your server to allow PHP in . html files, but that's outside our scope—so for now, just remember that, if you want to write PHP, you want to be working with .

Why are my PHP files showing as plain text?

phpinfo(); ?> are disabled by default. So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.


2 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, 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);
like image 163
jeroen Avatar answered Sep 22 '22 16:09

jeroen


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

    for ($i = 0; $i < 10; $i++) {
            $topten_sites[] = $sites_array[$i];
    }
like image 31
Mieszko Malawski Avatar answered Sep 24 '22 16:09

Mieszko Malawski