Michiel Nuyts Michiel Nuyts - 2 months ago 9
PHP Question

PHP Simple Calculation with an Array

So i have a simple for loop to get this result from any given number (get).

1 + 2 + 3 + 4 = 10

$num = intval($_GET["number"]);
$total = 0;

for ($i = 1; $i <= $num; $i++) {

echo $i;

if ($i != $num) {
echo " + ";
}
$total += $i;
}
echo " = " . $total;


Now I want to show the calculation of every step

1 + 2 = 3

1 + 2 + 3 = 6

1 + 2 + 3 + 4 = 10

And it should be done with an Array, but I can't seem to figure out the Algorithm.
I think I'm overlooking something simple here.

Answer

Try something like this:

<?php
$num = intval($_GET["number"]);

//add all numbers to an array
$numbers = array();
for ($i = 1; $i <= $num; $i++)
{
  $numbers[] = $i;
  //show each array element with ' + ' in between the elements
  echo implode(' + ', $numbers);

  //show total sum
  echo " = " . array_sum($numbers) . "\n";
}
?>

Note that this does not work, if $_GET['number'] is zero or even below zero.

Comments