Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function that does the same. So please, no code examples.
That sounds like a job for array_diff.
Returns an array containing all the
entries from array1 that are not
present in any of the other arrays.
array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
print_r( array_diff($arr1, $arr2) );
What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);
print_r( array_merge($diff1, $diff2) );
Note: This method will only work on arrays with numeric keys.
$diff = array_diff($array1, $array2);
array_diff()
Just to clarify as I was looking into this question the answers of #Jon and #Dallas Caley are both correct depending on the domain of your arrays.
If the array against what you are comparing is the full domain of your results then a simple array_diff will suffice as per #Jon answer.
If the array against what you are comparing is NOT the full domain of your results then you should go with the double array_diff as per #Dallas Caley 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)
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}
Up front, I would like to clarify that I am not looking for a workaround to find max--I already have the solution for accomplishing that goal. What I am curious about is why max(array_push()) doesn't work.
I have an array with many values in it, and want to find the max of specific values within that array. Existing array:
$array1 = array(2,6,1,'blue','desk chair');
The basic idea is to create a new array consisting of those specified values, and then find the max of that new array. I attempted to make this effort operate all on one line:
$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//this doesn't work at all, since $array2 doesn't already exist, as per the PHP manual
I changed to code to first create $array2, but didn't assign values at that time, just to see if the code works.
$array2 = array();
$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//$array2 is populated, but $max is not assigned
The obvious solution is to assign values to $array2 at creation and then use max() by itself. I'm just curious as to why max(array_push()) doesn't find max, since compounded functions normally operate from inside to outside.
Thank you.
max needs an array to work with but array_push returns an integer and actually uses the provided array by reference, you have to do :
$array2 = array();
array_push($array2, $array1[0], $array1[1], $array1[2])
$max = max($array2);
Alternatively do:
$array2 = array($array1[0], $array1[1], $array1[2]);
$max = max($array2);
A 3rd option (though not the cleanest one):
$array2 = array();
$max = max($array2 = array_merge($array2, [$array1[0], $array1[1], $array1[2]]));
For reference, see:
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.array-push.php
You could also use array_slice():
$max = max(array_slice(
$array1,
0,
3
));
if
the values you are interested in are in a sequence
you know offset and length of the sequence
For reference, see:
http://php.net/manual/de/function.array-slice.php
http://php.net/manual/de/function.max.php
For an example, see:
https://3v4l.org/nMK1Z
This question already has answers here:
Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion
(2 answers)
Closed last month.
I have two arrays:
$array1 = array("A","One","C","Z");
$array2 = array("B","K","2","5");
Is there some built-in PHP way to get a final array with (I don't know how to say it, maybe 1-1 correspondence addition) alternate keys appended to each other like this
$final_array = array("A","B","One","K","C","2","Z","5");
If I use array_merge, I get:
$final_array = array("A","One","C","Z","B","K","2","5")
But that's exactly what an array_merge does. Is there any workaround other than looping?
Try this:
$array1 = array(1,3,5,7);
$array2 = array(2,4,6,8);
$final_array = array_merge($array1,$array2);
sort($final_array);
print_r($final_array);
Hope this helps. Sorted the array using the sort function.
I am trying to compare two non-associative arrays to create a new array with the matches.
This is what I have though:
//This array has several entries
$a_firstarray = Array();
//This array has less entries than the first array
$a_secondarray = Array();
//This array should contain the matches of the first array and the second array in no particular order
$a_mergedarray
for($i=0;$i <=count($a_firstarray);$i++){
for($a=0;$a <=count ($a_secondarray);$a++){
if($a_firstarray[$i] == $a_secondarray[$a]){
$a_mergedarray[] = $a_activecategory[$i];
}
}
}
It doesn't work for some reason. I am also sure that PHP has some sort of function that does this. Any ideas? thanks in advance.
This is known as the "intersection" of two arrays. PHP provides array_intersect.
use array_intersect.
$result = array_intersect($array1, $array2);
Are you looking for array_intersect()?
http://php.net/manual/en/function.array-intersect.php