ShanjayG
ShanjayG

Reputation: 1023

How to get a total value from a loop result for integers in php. without Javascript of Jquery

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

Upvotes: 0

Views: 690

Answers (2)

ethan
ethan

Reputation: 975

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;
?>

Upvotes: 1

Anonymous
Anonymous

Reputation: 12017

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.

Upvotes: 1

Related Questions