Reputation: 137
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
Reputation: 6638
IMO, use array_map()
$sal=0;
$sal = array_sum(array_map(
function($item){
return $item->Salary;
},
$variable));
Upvotes: 0
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
Reputation: 3302
try this
$sal = 0;
foreach($variable as $key => $value){
$sal += $value->Salary;
}
echo $sal;
Upvotes: 1