$a = array("a","b");
$b = array("a"=>"one", "b" => "two","c"=>"three");
I need help in finding the difference between two arrays one with key and another without key.
required output
"c"=>"three"
Use array_diff_key() and array_flip():
$difference = array_diff_key(
$b,
array_flip($a)
);
For reference, see:
http://php.net/manual/en/function.array-diff-key.php
http://php.net/manual/en/function.array-flip.php
For an example, see:
https://3v4l.org/YgNhB
Every array has keys. Even if you have not set them.
So, your arrays look like this:
$a = array(0=>"a",1=>"b");
$b = array("a"=>"one", "b" => "two","c"=>"three");
And you trying to compare the values of one array with the keys of the other.
That's why localheinz is using array_flip() in his answer.
Related
Recently, I encountered some problem on comparing 2 nested arrays. I have tested to use array_diff_assoc to compare 2 arrays but it return me incorrect. Below are couple scenarios that I am attempt to compare these 2 nested array in php.
$arr1 = ["colorFamily"=>[]];
$arr2 = ["colorFamily"=>["blue","black"]];
$diff = array_diff_assoc($arr1,$arr2);
The $diff is expected to return below;
["colorFamily"=>[]]
Unfortunately, it return below:
[]
Aside from that, there are more complex scenario will be used in the comparison such as
$arr1 = ["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"],["value"=>"apple"]]];
$arr2 = ["colorFamily"=>["blue","black"],"descriptionMeasurement"=>[["label"=>"orange"]]];
Above scenario, it should return
["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"]]].
In short, anything occurs in $arr1 and it is not occurs in $arr2, should return in the $diff array.
I hope you guys can help me to resolve this problem, I have been stucking for weeks.
With array_diff you should always put the array with the missing values first, otherwise it doesn't return anything.
Also it can't see past the first array. So something like this will work:
$diff = array_diff_assoc($arr2["colorFamily"], $arr1["colorFamily"])
You could also use the following. array_map is used to index the keys:
$missing = array_map('unserialize', array_diff(array_map('serialize', $arr2), array_map('serialize', $arr1)));
(credits: Use array_diff_assoc() or get difference of multidimensional arrays)
Is there a way to combine boolean arrays:
$array1: ['prop1'=>T, 'prop2'=>F, 'prop3'=>T, 'prop4'=>F, 'prop5'=>T]
$array2: ['prop1'=>T, 'prop2'=>F, 'prop3'=>F, 'prop4'=>T]
Into
$array3: ['prop1'=>T, 'prop2'=>F, 'prop3'=>T, 'prop4'=>T, 'prop5'=>T]
Using the OR comparison?
I thought using $array3 = $array1 | $array2 would work but it returns a single value.
I feel like this could be a duplicate but I failed to find the same question on SO.
While each array have the same key you can use foreach loop to loop through the first array check if equally then you set the key and value to result array else if not equally then use the one with true value
$result=array();
foreach($array1 as $key=>$value){
if($array1[$key]==$array2[$key] || $array2==undefined){
$result[$key]=$value;
}
else{
$result[$key]=($array1[$key]==True)?$array1[$key] : $array2[$key];
}
}
Then loop through second array to see if the key is undefined in first to add the key value from second array
foreach($array2 as $key=>$value){
if ($array1[$key]==undefined){
$result[$key]=$value;
}
}
This is the shortest solution I can think of. And it's really not that complicated :). First we add the two arrays to make sure all keys exist in $result. Then we use the array_walk to perform the logical operation.
We need 3 arguments. The first is the $result variable we want to manipulate.
The third argument gets passed to our callback. We again use an array sum to ensure all keys are set, but this time $array2 gets the precedence.
The second is our callback. We get each value from the preliminary result by reference (&), each key by value, and our wish as a third parameter. The function itself is really simple we just set $v to whatever operation we want to implement. || for OR, && for AND or xor for XOR (but xor needs additional parentheses, see Operator precedence).
Demo
$array1 = ['prop1'=>TRUE, 'prop2'=>FALSE, 'prop3'=>TRUE, 'prop4'=>TRUE];
$array2 = ['prop1'=>TRUE, 'prop2'=>TRUE, 'prop3'=>FALSE, 'prop5'=>FALSE];
$result = $array1 + $array2;
array_walk($result, function(&$v, $k, $a){
$v = $v || $a[$k]; //Here you can change the operation
}, $array2+$array1);
var_dump($result);
So far I have done the following:
$row = mysql_fetch_assoc($result);
$row2 = mysql_fetch_assoc($result);
$duplicates = array_intersect($row, $row2);
How do I combine the 2 arrays and make a new one that just contains one instance of the previously repeated variables? (so if array $row contained the variable 'apple' 2 times and the array $row2 contained the variable 'apple' 3 times, in the new, merged array, 'apple' would only appear once.
edit: I didn't realize that the array_merge() function works differently for numbers than compared to strings. I gave the 'apple' example above but my arrays are dealing with product IDs which are numbers. PHP manual says
If, however, the arrays contain numeric keys, the later value will not
overwrite the original value, but will be appended.
and I need help in merging arrays with numbers, what should I do?
You can use
$c = array_merge($a, $b);
http://php.net/manual/en/function.array-merge.php
if you want to remove duplicate values after the merge then use array_unique();
so...
$c = array_unique(array_merge($a, $b));
I have two sequential (non-associative) arrays whose values I want to combine into a new array, ignoring the index but preserving the order. Is there a better solution (i.e. an existing operator or function) other than do the following:
$a = array('one', 'two');
$b = array('three', 'four', 'five');
foreach($b as $value) {
$a[] = $value;
}
Remark: The '+' operator doesn't work here ('three' with index 0 overwrites 'one' with index zero). The function array_merge has the same problem.
array_merge is what you want, and I don't think you are correct with that overwriting problem. From the manual:
If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
$a + $b on two arrays is the union of $a and $b:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
So use array_merge to merge both arrays:
$merged = array_merge($a, $b);
How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?
$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);
$C = array_intersect($A,$B); //equals (1,2,3,4)
$A = array_diff($A,$B); //equals (5,6,7,8)
Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.
You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.
Edit:
For example:
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
Source
Dear easy and clean way
$clean1 = array_diff($array1, $array2);
$clean2 = array_diff($array2, $array1);
$final_output = array_merge($clean1, $clean2);
See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.
Hey, even better solution: array _ uintersect.
This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.
Try to this
$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
$b = array(1=>'a',6=>'b',2=>'y',3=>'z');
$c = array_intersect($a, $b);
$result = array_diff($a, $c);
print_r($result);