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

StackOverflow https://stackoverflow.com/questions/22158187

  •  19-10-2022
  •  | 
  •  

Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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;
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top