Calculate total sum of all values from loop

<?php
    function calsum($start,$end,$inc){
        $sum = 0;
        for($i=$start; $i<=$end; $i+=$inc){
            echo "<pre>";
            echo $i;
            $sum = $sum + $i;
            echo "<br>";
        }
        echo $sum;
    }
   
    calsum(1,3,1);
?>

There is an user defined function called calsum(); In this this function total three parameters has been taken.
We will run a loop in this function. User's input will be the start value, end value, and the increment value.
Here user want to start loop from 1 and want to end to 3 and the increment gap will be one. So we will run the loop and show the output from 1 to 3 and we will get increment gap 1. But here we also want to get the total sum of the loop. So at first of all on the upper of loop we have declared a initial variable named $sum.
And which initial value is 0. And the value will increase with each rotation of loop. After end of the loop we will echo $sum; and we will get the total sum of loop as output.

Comments

Popular posts from this blog

WP register_post_type() with custom CMB2 meta box

Git post receive setup at server for git push to the production from local machine