PHP Merge (Add) Two Arrays by Same Key - php

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);

Related

Merge column values from two arrays to form an indexed array of associative arrays

I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)

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;
}
}

sum and minus array function 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.

How can I group same values in a multidimention array?

How can I group same values in a multidimention array?
I want this
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world'),
array('a' => 2, 'b' => 'you')
)
to become
array(
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world')
),
array('a' => 2, 'b' => 'you')
)
function array_gather(array $orig, $equality) {
$result = array();
foreach ($orig as $elem) {
foreach ($result as &$relem) {
if ($equality($elem, reset($relem))) {
$relem[] = $elem;
continue 2;
}
}
$result[] = array($elem);
}
return $result;
}
then
array_gather($arr,
function ($a, $b) { return $a['a'] == $b['a']; }
);
This could be implemented in a more efficient matter if all your groups could be reduced to a string value (in this case they can, but if your inner arrays were something like array('a' => ArbitraryObject) they could not be).

Categories