alcapone
alcapone

Reputation: 35

How to add values in foreach statement (PHP)

I have a table named tbl_grade that has this data for example

id   | studentid   |   compid   |  grade
1    | 1009123456  |     1      |  90
2    | 1009123457  |     2      |  95
3    | 1009123458  |     2      |  90

and I have this line of code in my model

public function gradeSum($studentid)
{
    $this->db->where('studentid',$studentid);
    $query = $this->db->get('tbl_grade');
    return $query->result();
}

in my view:

<?php foreach ($this->UserModel->gradeSum($student->studentid) as $studentgrade):
   if($studentgrade->compid==2){
       echo $studentgrade->grade; //the code for the addition of the grades should be put here but for the meantime i just echoed the grades
   }
endforeach;?>

the foreach statement would give me 95 and 90, which is correct. But I want to echo the sum of it. I put echo $sum->grade + $sum->grade; but obviously it didnt work so what is the correct syntax so that i could echo the sum of the values?

Upvotes: 0

Views: 57

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133380

Just use a temp var for adding

  <?php 
    $mySum = 0;
    foreach ($this->UserModel->gradeSum($student->studentid) as $studentgrade):
    if($studentgrade->compid==2){
         echo $studentgrade->grade; //the code for the addition of the grades should be put here but for the meantime i just echoed the grades
         $mySum = $mySum + $studentgrade->grade;
    }
    endforeach;
    echo $mySum;
?>

Upvotes: 1

Related Questions