Maybe I'm going insane, but I could have sworn that there was an PHP core function which took two arrays as arguments:
$a = array('1', '3');
$b = array('1'=>'apples', '2'=>'oranges', '3'=>'kiwis');
And performs an intersection where the values from array $a
are checked for collisions with the keys in array $b
. Returning something like
array('1'=>'apples', '3'=>'kiwis');
Does such a function exist (which I missed in the documentation), or is there a very optimized way to achieve the same thing?
The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.
The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order. For example. Input: A[] = {1,4,3,2,5, 8,9} , B[] = {6,3,2,7,5} Output: {3,2,5}
try using array_flip {switches keys with their values} and then use array_intersect() on your example :
$c = array_flip($b); // so you have your original b-array
$intersect = array_intersect($a,c);
I'm not 100% clear what you want. Do you want to check values from $a against KEYS from $b?
There's a few intersect functions:
http://php.net/manual/en/function.array-intersect.php http://www.php.net/manual/en/function.array-intersect-key.php
But possibly you need:
http://www.php.net/manual/en/function.array-intersect-ukey.php so that you can define your own function for matching keys and/or values.
Do a simple foreach
to iterate the first array and get the corresponding values from the second array:
$output = array();
foreach ($a as $key) {
if (array_key_exists($key, $b)) {
$output[$key] = $b[$key];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With