Array comparision in php to get only difference - php

Following Below are two arrays which i wanna compare and remove the same values something like array_diff() Function and i want to store the result in third array
$array1 = Array([0] => Array([a] => XYZ,[b] => ABC))
$array2 = Array([0] => Array([a] => XYZ,[b] => ABC),[1] => Array([a] => PQR,[b] => XYZ))
$array3 = array_diff($array1,$array2);
//$array3 value must return this value Array([1] => Array[a]=> PQR,[b] => XYZ)
I don't know what i am doing wrong but i am getting error that array cannot be converted into string. Can anyone help me with this?
Thanks in advance

If you are sure that your $array2 will always contain more elements than $array1 then here is your solution:
$array1 = array(array('a' => 'XYZ','b' => 'ABC'));
$array2 = array(array('a' => 'XYZ','b' => 'ABC'),array('a' => 'PQR','b' => 'XYZ'));
$limit = count($array2);
$array3 = array();
for($i=0;$i<$limit;$i++){
if(empty($array1[$i]))
$array3[] = $array2[$i];
$array3[] = array_diff($array1[$i],$array2[$i]);
}
foreach($array3 as $k=>$a3){
if(empty($a3)||($a3===NULL))
continue;
$result[$k] = $a3;
}
var_dump($result); //array(1) { [1]=> array(2) { ["a"]=> string(3) "PQR" ["b"]=> string(3) "XYZ" } }
Please note that array_diff works on 1D array and you was providing 2D arrays as parameter and that's why it wasn't working.
Also your way of defining $array1 and $array2 is wrong, please check this solution for right syntax.
I hope it helps

Related

Split an array into two arrays based on identical values

I have this array:
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this $arrayAll array into $array1 - that will contain everything with value 1 and $array2 - that will contain everything with value 2 so in the end I will have:
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
and
$array2 = [
'158' => '2',
'160' => '2'
];
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?
This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
https://3v4l.org/6en6l
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
https://3v4l.org/jbvBf
Use foreach and compare each value and assign it to a new array.
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
Demo
The simplest thing to do is to use a foreach loop.
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '<br>';
echo var_dump($array2);
Use indirect reference:
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "<pre>";
print_r($array1);
print_r($array2);
echo "</pre>";
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
With the conditions you mentioned just build two arrays, you can use array_keys with the second parameter that accepts a search value
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
If you don't want to use array_keys, go for an iteration
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
And that's it.
Check this link for array_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
The array you will return
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
The var_dump, in this case, will look like this
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like $array1, $array2 or the $key references to the value as in the last solution
The simplest solution for separating an array into others based on the values involves:
Getting its unique values using array_unique.
Looping over these values using foreach.
Getting the key-value pairs intersecting with the current value using array_intersect.
Code:
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
Advantage:
The advantage of this answer when compared to other given answers is the fact that it uses array_unique to find the unique values and therefore iterates only twice instead of n times.
Check out a live demo here.

How to add subvalues to a new array? [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 5 months ago.
I have an array with every containing value being another array with one value. I was looking for a way to flatten the array and succeeded but somehow I am having this feeling that it can be done better. Is this the best way or can it still be improved?
<?php
$array = array(
'1' => array('id' => '123'),
'2' => array('id' => '22'),
'3' => array('id' => '133'),
'4' => array('id' => '143'),
'5' => array('id' => '153'),
);
array_walk_recursive($array, function($v, $k) use (&$result) {
$result[] = $v;
});
You can achieve that using the array_map function:
$func = function($value) {
return $value['id'];
};
$array2 = array_map($func, $array);
Or if you want to keep it in one line do:
$array2 = array_map(function($value) { return $value['id']; }, $array);
This will return the array flattened and keeps your initial keys:
array(5) {
[1]=>
string(3) "123"
[2]=>
string(2) "22"
[3]=>
string(3) "133"
[4]=>
string(3) "143"
[5]=>
string(3) "153"
}
If you don't want to keep the keys, then call the following at the end:
$array2 = array_values($array2);
You can use array_map() passing null as the first argument while unpacking the passed array with the splat operator and grab the first element of the result:
$result = array_map(null, ...$array)[0];
Another option would be to use array_column() which creates an array from a single column of a given multidimensional array - feed it your array and column key, e.g.:
$result = array_column($array, 'id');
Output for either:
print_r($result);
Array
(
[0] => 123
[1] => 22
[2] => 133
[3] => 143
[4] => 153
)
This is what I would do. Its cleaner:
$array = array(
'1' => array('id' => '123'),
'2' => array('id' => '22'),
'3' => array('id' => '133'),
'4' => array('id' => '143'),
'5' => array('id' => '153'),
);
foreach($array as $key => $arr){
$result[] = $arr['id'];
}
If the depth won't ever change a foreach loop would likely be faster. That anonymous function has some overhead to it and it really shows the longer your array gets.
If the depth is variable as well, however, then this is the fastest way to traverse and flatten.

issue while merging two arrays using array_merge function

I have two associative array.
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
I am merging them using array_merge.
$Array3 = array_merge($Array1, $Array2);
Now value of $Array3 is like this.
Array
(
[abc] => abc
[def] => def
[0] => 123
[1] => 456
)
It looks really odd until I read php manual which says Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. array_merge manual
My questing How can I merge both array without loosing their associative keys.
Both array can have common KEYS and I don't want to loose my information also. :(
By +:
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
var_dump($Array1 + $Array2);
This will preserve the index, but note this will not overwrite the value of the first array if same key exists in first array.
And if you want the overwrite working, then there is array_replace function for this:
var_dump(array_replace($Array1, $Array2));
Try this code :) it will work
function my_merge($array1,$array2)
{
foreach($array2 as $key => $value)
{
$array1[$key] = $value;
}
return $array1;
}
$Array1 = array(
'abc'=> 'abc',
'def'=> 'def'
);
$Array2 = array(
'123'=> '123',
'456'=> '456'
);
$Array3 = my_merge($Array1, $Array2);
For associative arrays, use
$result = $Array1 + $Array2;
-but note, that for numeric keys this will also re-index:
$Array1 = array(
'abc',
'def'=> 'def'
);
$Array2 = array(
'123',
'456'
);
var_dump($Array1 + $Array2);
//array(3) { [0]=> string(3) "abc" ["def"]=> string(3) "def" [1]=> string(3) "456" }
If you have same keys in your arrays, you can use:
$result = array_reduce(array_keys($Array1), function($c, $x) use ($Array1)
{
$c[$x] = isset($c[$x])
?array_merge((array)$c[$x], [$Array1[$x]])
:$Array1[$x];
return $c;
}, $Array2);

PHP array_merge() function

I have some problems during working with arrays using array_merge function. Here an example:
First example:
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
var_dump(array_merge($first, $second));
Result is:
array(4) { ["01"]=> int(1) ["03"]=> int(73) [0]=> int(11) [1]=> int(23) }
Expected:
array(4) { ["01"]=> int(1) ["03"]=> int(73) [14]=> int(11) [15]=> int(23) }
Second example:
$first = array('01'=>3, '03'=>10);
$second = array('05'=>44, '07'=>3);
var_dump(array_merge($first,$second));
Result is(as expected):
array(4) { ["01"]=> int(3) ["03"]=> int(10) ["05"]=> int(44) ["07"]=> int(3) }
Third example:
var_dump(array_merge(array("somekey"=> array("some value"))));
Result is(as expected):
array(1) { ["somekey"]=> array(1) { [0]=> string(10) "some value" } }
Fourth example:
var_dump(array_merge(array("34"=> array("some value"))));
Result is:
array(1) { [0]=> array(1) { [0]=> string(10) "some value" } }
Expected:
array(1) { [0]=> array(1) { ["34"]=> string(10) "some value" } }
var_dump(array_merge(array("34"=> array("some value"))));
As you can see from third and fourth examples I set string for keys but the result was not as expected.
What is wrong or incorrect of understanding?
Thanks for helping.
Edited. Why (example first and second) the result is different, but the keys are string and consist of only with digest?
Quoting from the manual:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.
Values in the input array with numeric keys will be renumbered with
incrementing keys starting from zero in the result array.
Keys with a leading zero are being treated as strings, while numeric keys without a leading zero are being treated as numeric
If you want to retain the keys exactly as they are:
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
var_dump(
array_combine(
array_merge(
array_keys($first), array_keys($second)
),
array_merge(
$first, $second
)
)
);
as long as keys are unique between $first and $second
Definition : Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
INPUT
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
OUTPUT
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
Hope it helps:)
Try array_merge() like below:-
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
$output = array_merge($first, $second);
print_r($output);
EDIT:-
$first = array('01' => 1, '03' => 73);
$second = array('14'=>11, '15' => 23);
$output = $first + $second;
print_r($output);

php -Merging an Array

I have two array which i want to merge in a specific way in php.
So i need your help in helping me with it as i tried and failed.
So say i have two arrays:
$array1= array(
"foo" => 3,
"bar" => 2,
"random1" => 4,
);
$array2= array(
"random2" => 3,
"random3" => 4,
"foo" => 6,
);
Now when during merging i would like the common key's values to be added.
So like foo exists in array1 and in array2 so when merging array1 with array 2 i should get "foo" => "9"
I better illustration would be the final array which looks like this:
$array1= array(
"foo" => 9,
"bar" => 2,
"random1" => 4,
"random2" => 3,
"random3" => 4,
);
So again i would like the values of the common keys to be added together and non common keys to be added to array or a new array
I hope i was clear enough
Thanks,
Vidhu
Something like that:
function mergeValues() {
$result = array();
$arraysToMerge = func_get_args();
foreach ($arraysToMerge as $array) {
foreach($array as $key => $value) {
$result[$key] += $value;
}
}
return $result;
}
$res = mergeValues($array1, $array2, $array3); // Can pass any ammount of arrays to a function.
foreach($array1 as $k => $v)
{
If (isset($array2[$k]))
$array1[$k] += $array2[$k];
}
foreach($array2 as $k => $v)
{
If (!isset($array1[$k]))
$array1[$k] = $array2[$k];
}

Categories