Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation causing timeout

Below I have a segment of my code that I recently added to my PHP, which takes an array of integers ($naEUS) and iterates though it, appending the numbers with commas in between with a few exceptions for the start and finish. The end result should be a string that looks like this: ( ### , ### , ### , ### )

    $num = count( $naEUS[$f] );
    $resultsFields_values = "(";
    for( $b = 0; $b < $num; $b++ )
    {
        if( $b = 0 )
        {
            $resultsFields_values = substr_replace( $resultsFields_values, " {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
        }
        $resultsFields_values = substr_replace( $resultsFields_values, ", {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
    }
    $resultsFields_values = substr_replace( $resultsFields_values, ")" , ( strlen($resultsFields_values) ), 0);

I realize there are plenty of threads addressing string concatenation, but they only address part of my problem. I know this is a horribly inefficient way of doing this. and they show a better way of doing it, but that's easy to find.

What I really want to know is why it took my 5 second run time PHP to it's 30 second timeout.

Of course, better solutions are also welcome.

like image 725
Joshua Avatar asked May 18 '26 23:05

Joshua


1 Answers

for( $b = 0; $b < $num; $b++ )
    if( $b = 0 )

With $b = 0, you're resetting the loop back to zero on every iteration. = is for assignment, == is for equality testing.

like image 97
Marc B Avatar answered May 20 '26 14:05

Marc B