0

When the number 6 is giving I need to calculate till 6: for example: 1+2+3+4+5+6=21. I also need to add the sums of each to an array like: 1+2=3, 1+2+3=6, 1+2+3+4=10, ...

I have tried to make the while loop to be printed and this working fine but nog for array purpose:

   <?php
  $number = $_POST['number'];
  $i = 1;
  $cal = 0;
  $tussenBerekening = array();

  while ($i <= $number) {
    echo $i;
    $cal = $cal + $i;
    array_push($tussenBerekening, $cal);
    if ($i != $number) {
      echo " + ";
    } else {
      echo " = " . $cal;
    }
    $i++;
  }
?>

This is my new code, it prints, but no total sum.

<?php
  $number = $_POST['number'];
  $i = 2;
  $cal = 0;
  $sum = 1;
  $berekeningen = array();


  while ($i <= $number) {
    $sum .= "+" . $i;
    array_push($berekeningen, $sum);
    $i++;
  }

  print_r($berekeningen);

 ?>

1 Answer 1

1

Here's a solution:

$i = 1;
$number = 6;
while ($i <= $number) {
    // generate array with values from 1 to $i
    $array = range(1, $i);
    // if there're more than 1 element in array - output sum
    if (count($array) > 1) {
             // 1+2+... part                // sum of elements of array
        echo implode('+', $array) . ' = ' . array_sum($array) . '<br />';
    }
    $i++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! That's a really pretty PHP-specific solution. The asker's going to look like a professional old-timer on his assignment :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.