Sum values in foreach loop php
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
Calculate foreach group in loop by 3 PHP
A (very) basic solution (for my tests, I fix the typo on February month name) :
function getNextMonth($month) {
$months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
$pos = array_search($month, $months);
if ($pos === false) {
throw new Exception('Invalid month');
}
if ($pos == 11) {
return 'January';
// should return also year + 1
}
return $months[$pos+1];
}
$i = 1;
$trimestreSum = 0;
$trimestres = [];
foreach($salaries as $month) {
$trimestreSum += $month['salary'];
if ($i % 3 == 0) {
array_push($trimestres, [
'month' => getNextMonth($month['month']),
'sum' => $trimestreSum,
]);
$i = 0;
$trimestreSum = 0;
}
$i++;
}
print_r($trimestres);
The result is
Array
(
[0] => Array
(
[month] => April
[sum] => 900
)
[1] => Array
(
[month] => July
[sum] => 1800
)
[2] => Array
(
[month] => October
[sum] => 2700
)
[3] => Array
(
[month] => January
[sum] => 2430
)
)
The getNextMonth may be the only piece of code you need to add to your own code :)
Pretty sure that there are shorter (and more elegant) solutions, but hope that helps anyway.
sum amounts obtained in foreach
You want the total to accumulate over all the loops, so you define it outside the loop and add to it each time around:
$total = 0;
foreach ($products as $product) {
$subtotal = $product['price']*$product['quantity'];
$total += $subtotal;
}
echo $total;
Sum of values in a foreach loop php
You could use array_sum()
with array_column()
to compute the total sum of "pay".
Then you could use array_map()
to compute the average of individual sum along the total sum.
$data = [
["pay" => "2010000"],
["pay" => "3010000"],
["pay" => "3920000"],
];
$sum = array_sum(array_column($data, 'pay'));
$out = array_map(function($item) use($sum) {
return ['finalResult' => $item['pay'] / $sum] ;
}, $data);
print_r($out);
Outputs:
Array
(
[0] => Array
(
[finalResult] => 0.2248322147651
)
[1] => Array
(
[finalResult] => 0.33668903803132
)
[2] => Array
(
[finalResult] => 0.43847874720358
)
)
Or :
$data = [
["pay" => "2010000"],
["pay" => "3010000"],
["pay" => "3920000"],
];
$sum = array_sum(array_column($data, 'pay'));
$out = array_map(function($item) use($sum) {
return $item['pay'] / $sum ;
}, $data);
print_r($out);
Output:
Array
(
[0] => 0.2248322147651
[1] => 0.33668903803132
[2] => 0.43847874720358
)
PHP - For each loop - skip if identical values (but still sum values)
Assuming the $input
array has at least two columns per row, namely 'CODE'
and 'VALUE'
, we can use the 'CODE'
as a key (which is intrinsically unique) to sum the values in our $output
array:
$output = array();
foreach($input as $row)
{
$key = $row['CODE'];
$value = $row['VALUE'];
$output[$key] = isset($output[$key]) ? $output[$key] + $value : $value;
}
print_r($output);
Please note that the above solution causes the $output
array to grow dynamically, which can be a (time) problem for large arrays. If this is the case, please consider pre-calculating unique values for $input[$i]['CODE']
$i=1 ... count($input)
so that you can pre-allocate the $output
array by using array_pad
.
Sum values in foreach loop in [php]
You could add sum
variable for both tot_Price
and unit_Price
and add in foreach loop
<?php $sum_tot_Price = 0 ?>
<?php $sum_unit_Price = 0 ?>
@foreach ($yourData as X_land)
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
<?php $sum_tot_Price += $X_land->tot_Price ?>
<?php $sum_unit_Price += $X_land->unit_Price ?>
@endforeach
<tr>
<td>Sum tot_Price {{ $sum_tot_Price}}</td>
<td>Sum unit_Price {{ $sum_unit_Price}}</td>
</tr>
Use Linq instead of nested foreach loops to sum values
You can use SelectMany,
var allLines = journal
.SelectMany(j => j.trans
.SelectMany(l => l.line)
.ToList();
var posVal = allLines.Where(x => x.val > 0).Sum(x => x.val);
var negVal = allLines.Where(x => x.val < 0).Sum(x => x.val);
Related Topics
Comparing Date from Variable to MySQL Date
How to Delete Multiple Redis Keys With the Same Pattern in PHP Using Phpredis
Count Same Values in Array and Combine into Array
Telegram Bots - How to Create Reply Menus With Icons Like Mypokerbot
In Laravel How to Get Data in One Query from 3 Tables
How to Get Filename from a Variable (Url) in PHP
Auto Update Cart on Click in Woocommerce
Difference Between Single-Quoted and Double-Quoted Strings in PHP
How to Apply Bindvalue Method in Limit Clause
PHP - Ssl Certificate Error: Unable to Get Local Issuer Certificate
Detect a Quotation in a String
How to Check, If a PHP String Contains Only English Letters and Digits
I Have Three Columns, I Want to Combine Them All in One Main_Table
Displaying a Base64 Images from a Database Via PHP
How to Count Occurrence of Duplicate Items in Array
How to Stop My PHP Form Resubmitting Input After Page Refresh