Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deepu07's avatar
Level 11

PHP Optimization

Hello Mates,

Here is my problem I was trying to optimize this code but got stuck up. any help or suggestion would be great. highly appreciated and thanks in advance.


//[1,2,3,4,5]
//[3,5,7,9]
//[8,12,16]
//[20,28]
//[48]

$arr = [1,2,3,4,5];

for ($j = 0; $j < count($arr)-1; $j++) {
	$arr0[$j] = $arr[$j] + $arr[$j + 1];
}

for ($i = 0; $i < count($arr0) - 1; $i++) {
	$arr1[$i] = $arr0[$i] + $arr0[$i + 1];
}

for ($i = 0; $i < count($arr1) - 1; $i++) {
	$arr2[$i] = $arr1[$i] + $arr1[$i + 1];
}

for ($i = 0; $i < count($arr2) - 1; $i++) {
	$arr3[$i] = $arr2[$i] + $arr2[$i + 1];
}

print_r($arr);
print_r($arr0);
print_r($arr1);
print_r($arr2);
print_r($arr3);
0 likes
9 replies
amirkamizi's avatar

rather than calling for loop 4 times, you could call while. OR even better, create a function and then go through the process recursively.

sr57's avatar

I was trying to optimize this code

speed execution ?

nb of iines ?

readability ?

Optimize mean at least to have define a criteria ...

deepu07's avatar
Level 11

@silencebringer @sr57 I just don't wanna write that many for loops I just wanna complete the execution in two for loops. Like, let say I have 1000 elements I don't want to write 1000 for loops.

sr57's avatar

Use an multi-dim array

for ( $n..
    for ($i...
		$arrs[$n,$i)=...
SilenceBringer's avatar
Level 55

@deepu07 something like

function awesomeFunction($arr)
{
    if (count($arr) < 2) {
        return $arr;
    }

    for ($i = 0; $i < count($arr) - 1; $i++) {
        $arr[i] += $arr[$i + 1];
    }

    array_pop($arr);

    // print_r($arr); // uncomment to see every step

    return awesomeFunction($arr);
}

print_r(awesomeFunction(awesomeFunction));
1 like
Sir Apfelot's avatar

I guess recursion would be the best idea, like @amirkamizi said. But my pascal class was 2 centuries ago, so I can't really help. :D

pSouper's avatar

good Q. I was wonderinfg that too. Is the out put supposed to be an integer of 48, an array of ['48'], pass each step to another function, return a collection of arrays or something else.

*one should not rule out the possibility of an XY Problem when asking for help (or proffering a solution).

Please or to participate in this conversation.