devendra
devendra

Reputation: 137

Addition of Value Stored in Variable in a Loop

I have a foreach loop. which has a variable. how to Add variable values in a single variable.

$sal = "";
foreach($variable as $key => $value){
   $sal= $value->Salary;
}
echo $sal;

Upvotes: 0

Views: 53

Answers (3)

Mohit Tanwani
Mohit Tanwani

Reputation: 6638

IMO, use array_map()

$sal=0;
$sal = array_sum(array_map(
                 function($item){
                     return $item->Salary;
                 }, 
       $variable));

Upvotes: 0

Sebastian
Sebastian

Reputation: 525

I'm assuming you're referring to concatenation, since you instantiate $sal = "" (as a string). Use the concatenating assignment operator.

$sal = "";
foreach($variable as $key => $value){
   $sal .= $value->Salary;
}
echo $sal;

Upvotes: 0

shubham715
shubham715

Reputation: 3302

try this

$sal = 0;
foreach($variable as $key => $value){
   $sal += $value->Salary;
}
echo $sal;

Upvotes: 1

Related Questions