Multiply value of 2 indexes in foreach loop - php

I want to multiply the values of 2 indexes in my foreach loop.
E.G.
foreach($items as $item)
{
$result=$item['foo']*$item['bar'];
}
Then I want to return the result of the sum of all the $result within the function. For example,there are 2 rows of results in the foreach loop, I want to sum them up and return $sum. Anybody knows how to do that?

$sum = 0;
foreach($items as $item)
{
$result=$item['foo']*$item['bar'];
$sum += $result;
}
return $sum;
Is this what you want. It will add all $result in $sum and return $sum if this code is in a function.

Related

Consolidate array of numbers without exceeding a predefined maximum value per element

I'm trying to combine numbers in an array by adding them so that the max value can only by 30.
For example, this is my array:
array(10,30,10,10,15);
After combining the numbers in the array to items with a max value 30, the result should be:
array(30,30,15);
How to achieve this?
I'm trying to combine numbers in an array by adding them so that the
max value can only by 30
So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:
First, sort them.
Second, keeping adding elements to sum till you are about to get a sum > 30.
Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.
Code:
<?php
$arr = array(10,30,10,10,15);
sort($arr);
$res = [];
$curr_sum = 0;
foreach($arr as $each_value){
if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
else{
$res[] = $curr_sum;
$curr_sum = $each_value;
}
}
$res[] = $curr_sum;
print_r($res);
Demo: https://3v4l.org/BYhuE
Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.
rsort($res);
$total = array_sum(array(10,30,10,10,15)); //assign sum totals from orignal array
$maxValue = 30; //assign max value allowed in array
$numberOfWholeOccurancesOfMaxValue = floor($total/$maxValue);
$remainder = $total%$maxValue;
//build array
$i=0;
while ( $i < $numberOfWholeOccurancesOfMaxValue ){
$array[] = $maxValue;
$i++;
}
$array[] = $remainder;
print_r($array);
You can loop only once to get this,
$temp = array(10,30,10,10,15);
natsort($temp); // sorting to reduce hustle and complication
$result = [];
$i = 0;
$maxValue = 30;
foreach($temp as $v){
// checking sum is greater or value is greater or $v is greater than equal to
if(!empty($result[$i]) && (($result[$i]+$v) > $maxValue)){
$i++;
}
$result[$i] = (!empty($result[$i]) ? ($result[$i]+$v) : $v);
}
print_r($result);
Working demo.
I believe finding most space-optimized/compact result requires a nested loop. My advice resembles the firstFitDecreasing() function in this answer of mine except in this case the nested loops are accessing the same array. I've added a couple of simple conditions to prevent needless iterations.
rsort($array);
foreach ($array as $k1 => &$v1) {
if ($v1 >= $limit) {
continue;
}
foreach ($array as $k2 => $v2) {
if ($k1 !== $k2 && $v1 + $v2 <= $limit) {
$v1 += $v2;
unset($array[$k2]);
if ($v1 === $limit) {
continue 2;
}
}
}
}
rsort($array);
var_export($array);
By putting larger numbers before smaller numbers before processing AND by attempting to add multiple subsequent values to earlier values, having fewer total elements in the result is possible.
See my comparative demonstration.
I believe #Clint's answer is misinterpreting the task and is damaging the data by summing all values then distributing the max amounts in the result array.
With more challenging input data like $array = [10,30,5,10,5,13,14,15,10,5]; and $limit = 30;, my solution provides a more dense result versus #nice_dev's and #rahul's answers.

Know the count of for-each loop before executing that loop

How may i know that - In php how many times the foreach loop will get run, before that loop get executed..In other words i want to know the count of that particular loop. I want to apply some different css depends upon the count.
Use the function count to get the amount of numbers in your array.
Example:
$array = array('test1', 'test2');
echo count($array); // Echos '2'
Or if you want to be an engineer for-sorts you can set up something like so:
$array = array('test1', 'test2');
$count = 0;
foreach ($array as $a) { $count++; }
And that can count it for you, and the $count variable will hold the count, hope this helped you.
Simply count() the array and use the output as a condition, like:
if (count($array) > 100) {
// This is an array with more than 100 items, go for plan A
$class = 'large';
} else {
// This is an array with less than 100 items, go for plan B
$class = 'small';
}
foreach ($array as $key => $value) {
echo sprintf('<div id="%s" class="%s">%s</div>', $key, $class, $value);
}

get total of multidimensional array

So i have an array which is created like this via a loop
foreach ($items as $item)
{
$item_arr[$id]['count'] = $item->rowcount;
}
Now what i want to do is get the sum of the counts. I know i can just use $sum += $item->rowcount; but i was wondering if there was a more efficient way using something like this outside the loop when the foreach is done:
$sum = array_sum($item_arr[]['count']);
But that doesn't work says it doesn't like [], is there a way to do it or is the best way just to keep count in the foreach loop. Just would like to keep the code cleaner and more readable but maybe its a stupid question?
Where did $id come from?
the best would be $sum += $item->rowcount;
$sum = 0;
foreach ($items as $item) {
$sum += $item->rowcount;
}
echo $sum;
You can use array_reduce() like this
function sum($carry, $item){
return $carry + $item['count'];
}
array_reduce($item_arr, "sum");
A variation of a theme perhaps but like array_reduce you could alternatively use array_walk
$total=0;
$arr=array(
array('count'=>23),
array('count'=>54),
array('count'=>91),
array('count'=>86)
);
array_walk( $arr, function( &$i, $k, &$t ){
$t += $i['count'];
}, &$total );
echo 'total:'.$total;

Add value of columns in foreach loop.

I have quantity in two diff tables . i want to add those quantities and update it into table3 amount column.
I have wrote this code but the value is showing 0
foreach($products as $key =>$value)
{
echo $totalquantity = $value->amount+ $value->QuantityAvailable;
$updtqry="UPDATE stock SET amount = $totalquantity where id_stock='".$value->id_stock."'";
mysql_query($updtqry);
}
I just want to know how to get a sum of array values within foreach loop
Well you get sum of two arrays containing numeric values like this:
$sum = 0;
foreach($amountArray as $amount) {
$sum += $amount;
}
foreach($amountArray2 as $amount) {
$sum += amount;
}
// update with $sum...
1.) If you want to find the sum of the elements of one particular array. You could use array_sum().
array_sum($array1);
2.) If you want to get the sum of two array you could do it the following way, provided the arrays are numerically indexed.
for($index=0; $index < count($array1); $index++) {
$array3[$index] = $array1[$index] + $array2[$index];
}
Here $array1 and $array2 are the values of which are to be added and stored in $array3.
3.) If the arrays are not numerically indexed then you could do this:
for ($counter=0;$counter<count($array1);$counter++) {
$array3[$counter] = current($array1) + current($array2);
next($array1); next($array2);
}
The number of the elements of the two arrays should be equal for it to work.

Can use Array_sum or loop and make sum?

Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?
$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;
$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'
Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.
One liner echo array_sum(array_column($a, "add"));

Categories