sum and minus array function php - php

What is the easiest way to achieve:
a => 1, b => 0, c=> 3
a => 0, b => 10, c=> 1
Sum
a => 1, b =>10, c=>4
and
Minus
a => -1, b=> 10, c=> -2
I hope my examples make it clear... If you have any questions please leave a comment

Sum:
$array1 = array('a' => 1, 'b' => 0, 'c' => 3);
$array2 = array('a' => 0, 'b' => 10, 'c' => 1);
$result = array();
foreach ($array1 as $key => $value)
$result[$key] = $value + $array2[$key];
You can implement the difference part similarly.

$sum = $minus = 0;
foreach ($arrays as $key=>$val)
{
$sum += $val;
$minus -= ($val*-1);
}

You want to add orsubstarct the values with same key.
Try to write function with array_walk
http://php.net/manual/en/function.array-walk.php
or put in a loop and add or substarct based on key.

Related

output of php array in a particular format

am trying to get output of following array in one format. its not getting
<?php
$distance_covered = array( '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
The above is my array
i want output in the following format
Output: Array ( [DRIVER_1] => 51, [DRIVER_2] => 33, [DRIVER_3] => 24, [DRIVER_4] => 67, [DRIVER_5] => 34 )
this is the sum of distance travelled by each driver in all trips
i tried code like this,anybody knows please help
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
print_r($res);
?>
This one works for me
$res = array();
foreach($distance_covered as $value)//the array which you have given us
{
foreach($value as $key => $number) //loop over array of date
{
if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
{
$res[$key] = array_sum($number);// Sum all distances of that driver
continue;//set the key and continue the foreach...
}
$res[$key] += array_sum($number);// Sum all distances of that driver
}
}
print_r($res);
die;
And the Output is
Array
(
[DRIVER_1] => 51
[DRIVER_2] => 33
[DRIVER_3] => 24
[DRIVER_4] => 67
[DRIVER_5] => 34
)
This should work:
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
foreach ($number as $n) {
if (isset($res[$key])) {
$res[$key] += $n;
} else {
$res[$key] = $n;
}
}
}
}
print_r($res);
Just traverse through array of arrays.
$distance_covered = array(
'1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
// Counting.
$merged = [];
foreach ($distance_covered as $day => $stats) {
foreach ($stats as $driver => $distances) {
if (!isset($merged[$driver])) {
$merged[$driver] = 0;
}
$merged[$driver] += array_sum($distances);
}
}
// Display.
echo "<pre>";
print_r($merged);
echo "</pre>";
You are close, but...
$res = array ();
foreach ( $distance_covered as $value ) {
foreach ( $value as $key=> $driver ) {
if ( isset($res[$key]) == false ){
$res[$key]=0;
}
$res[$key] += array_sum($driver);
}
}
print_r($res);
The first foreach simply splits the data down to the days.
The second one returns elements like $key = 'DRIVER_1' and $driver = array(3, 9).
If this is the first time you've encountered this driver, then you need to ensure that the element in $res exists, so set it to 0.
Once you know there is an element there, you can add in the sum of the values ( 3 & 9 in this case ) using the += array_sum($driver) bit. The += is simply adding to rather than having to say a=a+b, you can say a+=b.
[sarcastic voice] I can't believe everybody overlooked this convoluted function-based one-liner...
Code: (Demo)
var_export(array_map('array_sum', array_merge_recursive(...array_values($distance_covered))));
Output:
array (
'DRIVER_1' => 51,
'DRIVER_2' => 33,
'DRIVER_3' => 24,
'DRIVER_4' => 67,
'DRIVER_5' => 34,
)
*this is virtually guaranteed to process slower than any other posted answer.
Remove the first level associative keys (date strings) with array_values()
Unpack the array of arrays with the "splat operator" (...) and feed to array_merge_recursive() to group values
Sum the subarray values by calling array_sum() on each subarray with array_map()
(This is merely an exercise of thinking outside the box.)
Beyond that no one suggested using a null coalescing operator, so I'll post what that can look like:
$driver_totals = [];
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] = ($driver_totals[$driver] ?? 0) + array_sum($distances);
}
}
var_export($driver_totals);
And if you have a special scenario where you only need to know the distance for a single specific driver, you can call upon array_column() like this:
$target_driver = 'DRIVER_4';
$total_distance = 0;
foreach (array_column($distance_covered, $target_driver) as $distances) {
$total_distance += array_sum($distances);
}
echo "{$target_driver} drove for a distance of {$total_distance}";
*Notice that the order of the drivers within each date array is inconsequential because array_column() is smart enough to find the desired distance subarray.
Finally, if you declare a whitelist array of all possible drivers, you can:
control the order of the drivers in the output
avoid the iterated isset() conditions
ensure that drivers without any distance records are included in the output
Code:
$roster = ['DRIVER_6', 'DRIVER_5', 'DRIVER_4', 'DRIVER_3', 'DRIVER_2', 'DRIVER_1'];
$driver_totals = array_fill_keys($roster, 0);
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] += array_sum($distances);
}
}
var_export($driver_totals);

PHP Merge (Add) Two Arrays by Same Key

I have two arrays.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
I want to merge these two arrays and get following result.
$c = array('a' => 5, 'b' => 12, 'c' => 18);
What is the easiest way to archive this?
Thanks!
As mentioned in the comments, looping through the array will do the trick.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
$c = array();
foreach($a as $index => $item) {
if(isset($b[$index])) {
$new_value = $a[$index] + $b[$index];
$c[$index] = $new_value;
}
}
$c = array();
foreach ($a as $k => $v) {
if (isset($b[$k])) {
$c[$k] = $b[$k] + $v;
}
}
You need to check whether keys exist in both arrays.
You can simply use foreach as
foreach($b as $key => $value){
if(in_array($key,array_keys($a)))
$result[$key] = $a[$key]+$value;
}
You can easily do this by foreach loop, please see the example below
$c = array();
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
foreach ($a as $key => $value) {
$tmp_value = $a[$key] + $b[$key];
$c[$key] = $tmp_value;
}
print_r($c);

Count element in multidimensional array

I have one problem with PHP array. I have the following array:
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
I want to know how many element in total.
Ex:
echo count($arr); // result: 3
but I want: 7
I want to do this without loop.
Do any one know, please help?
Take one of this
$arr = array(
1 => array(1, 2),
2 => array(1, 2, 3),
3 => array(4, array(4, 4, 4))
);
// iterate over values to find out their size/
var_dump(array_reduce($arr, function($count, $inner_array)
{ return $count + sizeof($inner_array); }, 0));
// merge all value to one big array
var_dump(count(call_user_func_array('array_merge', $arr)));
// create new array with counts of items
var_dump(array_sum(array_map('sizeof', $arr)));
<?php
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$sum = 0;
foreach($arr as $a => $b) {
$sum += count($b);
}
echo $sum;
?>
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$count = 0;
foreach ($arr as $level) {
$count+= count($level);
}
echo $count;
If your array as follows you can use another method for get 7
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,8)
);
echo (count($arr, COUNT_RECURSIVE) - count($arr));

add the values of two different associative arrays in php . display unique key-values too in the result array [duplicate]

This question already has answers here:
How to sum all column values in multi-dimensional array?
(20 answers)
Closed 9 years ago.
i need to merge two associative arrays which may or may not contain same key,if key is same the values need to added and stored in the resultant array
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' = > 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
how to add the above two associative arrays and receive the following output/associative array -
$array2 = array(
'a' => 105,
'b' => 10,
'c' => 206,
'd' => 30,
'k' => 20
);
Try
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' => 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
$sums = array();
foreach (array_keys($array1 + $array2) as $key) {
$sums[$key] = (isset($array1[$key]) ? $array1[$key] : 0) + (isset($array2[$key]) ? $array2[$key] : 0);
}
print_r($sums);
$a3 = array_merge_recursive ($array1, $array2);
foreach ($a3 as $key => $value)
{
$a3[$key] = (is_array($value))?array_sum($value):$value;
}
for finding unique index value
$array2 =array_merge($array1,$array2);
and for finding unique value you can try
$array2 =array_unique(array_merge($array1,$array2));
I don't know if you can do this with an internal function but it is doable by simply iterating through both arrays.
function merge_add($array1, $array2)
{
$result = array();
merge_add_array($array1, $result);
merge_add_array($array2, $result);
return $result;
}
function merge_add_array($array, &$result)
{
foreach ($array as $key=>$value)
{
if (array_key_exists($key, $result))
{
$result[$key] += $value;
}
else
{
$result[$key] = $value;
}
}
}
$result = merge_add($array1, $array2);
The & will cause passing by reference
<?php
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' => 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
$keys = array_keys($array1 + $array2);
foreach ($keys as $key) {
$array2[$key] = isset($array1[$key]) && isset($array2[$key]) ? ($array1[$key] + $array2[$key]) : (isset($array1[$key]) ? $array1[$key] : $array2[$key]);
}
print_r($array2);

Get the name of the variable which has the highest/biggest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the highest value?
Thanks in advance.
Here is a solution to the question you asked:
$arr = compact('v1', 'v2', 'v3', 'v4');
arsort($arr);
$name = key($arr);
// get the value: ${$name}
However, having the variables stored in an array in the first place would make more sense. A better setup would be:
$arr = array('v1' => 543, 'v2' => 41, 'v3' => 1, 'v4' => 931);
arsort($arr);
$name = key($arr);
// get the value: $arr[$name]
Given four variables:
$a = 1;
$b = 3;
$c = 4;
$d = 2;
You can use compact to turn them into an associative array:
$array = compact('a', 'b', 'c', 'd');
var_dump($array); // array('a' => 1, 'b', => 3, 'c' => 4, 'd' => 2);
And then find the maximum key/value:
$max_key = $max_value = null;
foreach ($array as $key => $value) {
if (is_null($max_value) || $value > $max_value) {
$max_key = $key; $max_value = $value;
}
}

Categories