Nirav Patel
Nirav Patel

Reputation: 3

How do I count the sum of specified sum in $total

e.g. if I pass $total = 2 then it should calculate the sum of first two arrays.
sub1 + sub2

**HERE IS MY CODE **

<?php 
    $num = 2;
    $array = array();
    $total = 2;

    for($x=1;$x<=$num;$x++)
    {
         $result = array('sub1'=>rand(1,100),
                    'sub2'=>rand(1,100),
                    'sub3'=>rand(1,100),
                    'sub4'=>rand(1,100),
                    'sub5'=>rand(1,100));
               $array[] = $result;
    }  

    echo '<pre>'; print_r($array);

    ?>

Upvotes: 0

Views: 61

Answers (2)

Mo Shal
Mo Shal

Reputation: 1637

simply you can use for loop like this

$sum=0;

for($i=0;$i<$total;$i++){

$sum+=$result[$i];

}

Upvotes: 0

FastTurtle
FastTurtle

Reputation: 1777

try

<?php 
    $array = array();
    $total = 2;

    $result = array('sub1'=>rand(1,100),
                    'sub2'=>rand(1,100),
                    'sub3'=>rand(1,100),
                    'sub4'=>rand(1,100),
                    'sub5'=>rand(1,100));

    $temp_array = array_slice($result, 0, $total);   
        $sum = array_sum($temp_array);
        print_r($result);
        echo "sum of $total array is : ".$sum;

Output would be like :

Array
(
    [sub1] => 30
    [sub2] => 19
    [sub3] => 56
    [sub4] => 47
    [sub5] => 6
)
sum of 2 array is : 49 

https://eval.in/539097

should do the trick. hope it helps :)

Upvotes: 3

Related Questions