I found a question on google like this :
When given the input : 4, 7, 3, 6, 7
The output like this :
81
40 41
21 19 22
11 10 9 13
4 7
Try this,
<?php
$a = 4;
$b = 7;
$c = 3;
$d = 6;
$e = 7;
for($y = 1; $y<=5;$y++){
for($z=0; $z<$y; $z++){
$f = $a+$b;
$g = $b+$c;
$h = $c+$d;
$i = $d+$e;
$j = $f+$g;
$k = $g+$h;
$l = $h+$i;
$m = $j+$k;
$n = $k+$l;
$o = $m+$n;
}
}
echo $o.'<br/>';
echo $m.' '.$n.'<br/>';
echo $j.' '.$k.' '.$l.'<br/>';
echo $f.' '.$g.' '.$h.' '.$i.'<br/>';
echo $a.''.$b.' '.$c.' '.$d.' '.$e;
?>
<?php
$input = array(4, 7, 3, 6, 7);
$lines = rollup($input);
function rollup ($input) {
$return = array();
$line = array();
if (count($input) > 0) {
foreach ($input as $k=>$v) {
if (isset($input[$k+1]))
$line[] = $v + $input[$k+1];
}
$return = implode(' ', $input);
rollup($line);
}
if (!empty($return))
echo $return . '<br />';
}
?>
You can use this code
<?php
$arr = [4, 7, 3, 6, 7];
$count = count($arr);
$finalStr = "";
while($count>0){
$str = "";
foreach($arr as $key=>$val){
$arr[$key] = $arr[$key]+$arr[$key+1];
$str .="$val ";
}
$str .= "\n";
$finalStr = $str . $finalStr;
unset($arr[count($arr)-1]);
$count--;
}
echo $finalStr;
?>
Check live demo : https://eval.in/609908
Output is :
81
40 41
21 19 22
11 10 9 13
4 7 3 6 7
Just to give another solution, because I like 'puzzlers' like these, I'll give you this:
<pre>
<?php
//init
$input = [4, 7, 3, 6, 7];
$output = [$input];
//process
while(count($input) > 1) {
foreach($input as $key => $val) {
$key ? $input[] = $val + $prev : $input = array();
$prev = $val;
}
array_unshift($output, $input);
}
//output
array_walk($output, function($line){
echo implode(' ', $line) . "\n";
});
?>
</pre>
See it working here