Question

how to add a total of the numbers displayed as an integer from a loop. the loop result is not an increment. here is the problem.

<?php
    $i = 0;
    $num =1;

    while($i<=4){

     echo $num;
      $i++;
    }
 echo $num;
   ?>

So the result is something like this.

1 1 1 1

so my problem is how can i total the result which should be 4, and save it in a variable without incrementing. and even more confusing is. how to do the same when the value of $num is dynamic. Thank you very much. in advance

Was it helpful?

Solution

Just make an array then sum them:

<?php
    $i = 0;
    $num =1;

    while($i<=4){

     $nums[] = $num;
      $i++;
    }
    echo array_sum($nums); //Outputs 5
?>

This assumes that $num is always numeric.

OTHER TIPS

Alternatively, you could just iterate an output variable, based on the value of $num. Like so:

<?php
$num = 1; // or 2, or 3, or 4 or whatever
$output = 0;
for ($i=0; $i<=4; $i++) {
    $output += $num;
}
echo $output;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top