Add two arrays with the same length - php

I have two arrays,
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
what I want to achieve is to have a single array where the final form after adding the two arrays would be,
$arr_3 = array(01=>8, 02=>7, 03=>2);
I tried array_merge but it wasn't the solution.How would I attain the final form?

Try array_map. From the PHP Manual
array_map() returns an array containing all the elements of arr1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
$arr_3 = array_map('add', $arr_1, $arr_2);
function add($ar1, $ar2){
return $ar1+$ar2;
}
print_r($arr_3);
OUTPUT:
Array ( [0] => 8 [1] => 7 [2] => 2 )

A for loop should handle this:
$max = count($arr_1);
$arr_3 = array();
for($i = 0; $i < $max; $i++){
$arr_3[$i] = intval($arr_1[$i]) + intval($arr_2[$i]);
}
I'm sure there are many other ways to do this, but this is the first one that came to mind. You could also do a foreach loop:
$arr_3 = array();
foreach($arr_1 as $k => $v){
$arr_3[$k] = intval($v) + intval($arr_2[$k]);
}
I'm just winging it here, the foreach is a little tricky to avoid the cartesian effects. Worth a shot though.

If you require adding elements matching by their key not by their position, you could try this:
$array1 = array(1=>5, 2=>3, 3=>2);
$array2 = array(3=>3, 2=>4, 1=>0); //unsorted array
$keys_matched = array_intersect_key ( $array1 , $array2);
foreach ($keys_matched as $key => $value) {
$result[$key] = $array1[$key] + $array2[$key];
}
print_r($result); //Displays: Array ( [1] => 5 [2] => 7 [3] => 5

You would look through both arrays and add each value of each array together then add that result to another array.
foreach($array1 as $val1) {
foreach($array2 as $val2) {
array_push($newArray, intval($val1)+ intval(val2));
}
}

Related

How to delete array of element in array

I have two array. I want to remove if 2nd array exists in 1st array. For example
array1 = array ("apple","banana","papaya","watermelon","avocado");
array2 = array ("apple","avocado");
I want the output should be
Array ( [1] => banana [2] => papaya [3] => watermelon)
Here are some code that I'd tried.
foreach($array2 as $key){
$keyToDelete = array_search($key, $array1);
unset($array1[$keyToDelete]);
}
print_r($array1);
but the output is
Array ( [1] => banana [2] => papaya [3] => watermelon [4] =>avocado )
It only remove first element.
i also tried to do something like this
$result = array_diff($array1,$array2);
print_r($result);
but the output is it print all element in array1
Noted: I want the result need to be outside foreach loop
array_diff should be work.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$array_diff = array_diff($array1, $array2);
print_r($array_diff);
?>
DEMO
output will be.
Array ( [1] => banana [2] => papaya [3] => watermelon)
You can also try below solution. result will be same.. using in_array Check if first array value not in the second tester that value in the new array 'final_result' for results.
in_array support (PHP 4, PHP 5, PHP 7)
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$final_result = array();
foreach($array1 as $value){
if(!in_array($value, $array2)){
$final_result[] = $value;
}
}
print_r($final_result);
?>
DEMO
With the help of array_filter() we can do it easily. It filters elements of an array using a callback function.
array_filter() iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
Here we have used use($array2) clause to access the external variable inside callback function. $array2 is needed to filter out $array1.
$array1 = array("apple","banana","papaya","watermelon","avocado");
$array2 = array("apple","avocado");
$array1 = array_filter($array1, function($item) use($array2) { return !in_array($item, $array2); });
print '<pre>';
print_r($array1);
Demo
The fastest way to do this is to create a set(associative array) of elements in $array2 and iterate over $array1 and check if element in $array1 exists in our set or not using isset(). We take advantage of the method/algorithm technique called hashing.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$set = [];
foreach($array2 as $element){
$set[$element] = true;
}
$result = [];
foreach($array1 as $element){
if(!isset($set[$element])){
$result[] = $element;
}
}
print_r($result);
Demo: https://3v4l.org/PcS45

Array difference for multidimensional array with single array in php

I want difference of multidimensional array with single array. I dont know whether it is possible or not. But my purpose is find diference.
My first array contain username and mobile number
array1
(
array(lokesh,9687060900),
array(mehul,9714959456),
array(atish,9913400714),
array(naitik,8735081680)
)
array2(naitik,atish)
then I want as result
result( array(lokesh,9687060900), array(mehul,9714959456) )
I know the function array_diff($a1,$a2); but this not solve my problem. Please refer me help me to find solution.
Try this-
$array1 = array(array('lokesh',9687060900),
array('mehul',9714959456),
array('atish',9913400714),
array('naitik',8735081680));
$array2 = ['naitik','atish'];
$result = [];
foreach($array1 as $val2){
if(!in_array($val2[0], $array2)){
$result[] = $val2;
}
}
echo '<pre>';
print_r($result);
Hope this will help you.
You can use array_filter or a simple foreach loop:
$arr = [ ['lokesh', 9687060900],
['mehul', 9714959456],
['atish', 9913400714],
['naitik', 8735081680] ];
$rem = ['lokesh', 'naitik'];
$result = array_filter($arr, function ($i) use ($rem) {
return !in_array($i[0], $rem); });
print_r ($result);
The solution using array_filter and in_array functions:
$array1 = [
array('lokesh', 9687060900), array('mehul', 9714959456),
array('atish', 9913400714), array('naitik', 8735081680)
];
$array2 = ['naitik', 'atish'];
$result = array_filter($array1, function($item) use($array2){
return !in_array($item[0], $array2);
});
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => lokesh
[1] => 9687060900
)
[1] => Array
(
[0] => mehul
[1] => 9714959456
)
)
The same can be achieved by using a regular foreach loop:
$result = [];
foreach ($array1 as $item) {
if (!in_array($item[0], $array2)) $result[] = $item;
}

How to add 2 arrays and sort it

How can I turn:
$array1 = array(34=>"key1",54=>"key3",12=>"key2");
$array2 = array(44=>"key4",12=>"key2",1=>"key1");
into:
$array = ("key3"=>54,"key4"=>44,"key1"=>35,"key2"=>24);
How to add the value of the keys and sort by value?
You could flip the arrays, merge and sum matching key values, followed by a reverse sort:
$a1 = array(34=>"key1",54=>"key3",12=>"key2");
$a2 = array(44=>"key4",12=>"key2",1=>"key1");
function addRev($a1,$a2) {
$a1 = array_flip($a1);
$a2 = array_flip($a2);
$added = array();
foreach (array_keys($a1 + $a2) as $key) {
$added[$key] = #($a1[$key] + $a2[$key]);
}
arsort($added);
return $added;
}
print_r(addRev($a1, $a2));
Result:
Array
(
[key3] => 54
[key4] => 44
[key1] => 35
[key2] => 24
)
try this, I add explanations in comments
$array1 = array(34=>"key1",54=>"key3",12=>"key2");
$array2 = array(44=>"key4",12=>"key2",1=>"key1");
// fliping arrays
$a1r = array_flip($array1);
$a2r = array_flip($array2);
var_dump($a1r);
var_dump($a2r);
// adding the 2 arrays, final result in $a1r
foreach ($a2r as $key => $value) {
if (!isset($a1r[$key])) {
$a1r[$key] = 0;
}
$a1r[$key] += $value;
}
var_dump($a1r);
You can use array_merge() function for "adding" arrays.
http://php.net/manual/en/function.array-merge.php
For sorting, you can check this link:
Sorting an associative array in PHP

Compare Associative arrays - return unmatched values

I have 2 associative arrays, like below.
Array
(
[Turbine] => 0
[Nuts and Bolts] => 6
[Runner Blade] => 5
)
Array
(
[Nuts and Bolts] => 10
[Runner Blade] => 5
[Turbine] => 1
)
What I want to do is compare the two arrays and return ones that have the same key but a different value. Similar to array_intersect_assoc, but that returns all values that match which is not what I want. Using the examples above what I want to return is the difference between the 2 values, something like:
Array
(
[Nuts and Bolts] => 4
[Turbine] => 1
)
Something like this:
$ar1;
$ar2;
foreach ($ar1 as $k => $v) {
if (intval($ar2[$k]) != intval($v))
$ar1[$k] = abs($v - $ar2[$k]);
else
unset($ar1[$k]); // remove key with equal value
}
Try this...
$newArr = array();
foreach($arr1 as $k=>$v){
$dif = abs($arr1[$k] - $arr2[$k]);
if($dif) $newArr[$k] = $dif;
}
print '<pre>';
print_r($newArr);
This will do what you want:
array_intersect_key($array1, $array2)
$diff = array_diff_assoc($arr1, $arr2);
$result = array();
foreach(array_keys($diff) as $key){
$result[$key] = abs($arr1[$key] - $arr2[$key]);
}
var_dump($result);

Merge two sorted arrays and the resulting array should also be sorted

Let's say you have two arrays of arrays with the same structure but different count of arrays in them:
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
Now, the data in the $arr1 and $arr2 is sorted, and now what I would like it to merge these two arrays, so I did this:
$res = array_merge($arr1, $arr2);
And then I get an output like this:
1-b
2-a
5-c
3-e
But, I would like to have a sorted $res also like this:
1-b
2-a
3-e
5-c
I wonder if there's a function in PHP to do this automatically, without me having to write my own function? Or, please advise me on which is the best approach for this if I want to (later on) add sorting by the next parameter so the output would be like this
2-a
1-b
5-c
3-e
Thank you for all your help.
You can first merge the arrays and then sort the final array.
You are probably looking for a multi-sort function. I usually use this function (I found this functions somewhere on the internet years ago, credits go to the original author):
/*
* sort a multi demensional array on a column
*
* #param array $array array with hash array
* #param mixed $column key that you want to sort on
* #param enum $order asc or desc
*/
function array_qsort2 (&$array, $column=0, $order="ASC") {
$oper = ($order == "ASC")?">":"<";
if(!is_array($array)) return;
usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);"));
reset($array);
}
You can use it like this:
array_qsort2($res, 0, "ASC");
Why not simply call ksort($res) after your array_merge?
Since php v5.3 you can use anon functions in a more natural manner,
<?php
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
$res = array_merge($arr1, $arr2);
usort($res, function($a,$b) {
// php7
// return $a[0] <=> $b[0];
if ($a[0] == $b[0]) return 0;
return $a[0] < $b[0] ? -1 : 1;
});
print_r($res);
output
Array
(
[0] => Array
(
[0] => 1
[1] => b
)
[1] => Array
(
[0] => 2
[1] => a
)
[2] => Array
(
[0] => 3
[1] => e
)
[3] => Array
(
[0] => 5
[1] => c
)
)
You can use below function to merge two sorted arrays without array_merge() or sort().
<?php
$arr1 = [1,2,5,7,10,20,36,70,82,90];
$arr2 = [4,6,10,15,65,85,90,100];
function shortt($array1,$array2){
$array1_count = count($array1);
$array2_count = count($array2);
while ($array1_count || $array2_count)
{
$array1_empty = $array1 == [];
$array2_empty = $array2 == [];
if (!$array1_empty && !$array2_empty)
{
if (current($array1) < current($array2))
{
$array3[] = array_shift($array1);
$array1_count--;
}
else
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
elseif (!$array1_empty)
{
$array3[] = array_shift($array1);
$array1_count--;
}
elseif (!$array2_empty)
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
return $array3;
}
$newarr = shortt($arr1,$arr2);
print_r($newarr);
?>

Categories