Problem:
You have multiple arrays (see the following ones) and you want to find out any common values that exists in all of the arrays.
<?php $Sam = array('age'=>29, 'profession'=>"Web Developer", 'state'=>'NY'); $Jack = array('age'=>22, 'profession'=>"Web Designer", 'state'=>'NY'); $John = array('age'=>32, 'profession'=>"Junior Marketer", 'state'=>'NY'); ?>
Solution:
You can use array_intersect() function to accomplish it. This function gets the common values among multiple arrays, create an array with those values, and then return it. See the following example-
<pre> <?php $Sam = array('age'=>29, 'profession'=>"Web Developer", 'state'=>'NY'); $Jack = array('age'=>22, 'profession'=>"Web Designer", 'state'=>'NY'); $John = array('age'=>32, 'profession'=>"Junior Marketer", 'state'=>'NY'); $common = array_intersect($Sam, $Jack, $John); print_r($common); ?> </pre>
[wpdm_file id=108]
Output:
Array( [state] => NY )
How it works:
The array_intersect() function finds the common value “NY” that exists in all three arrays – $Sam, $Jack, and $John and returns that common value as an array. We name the array as $common. Then, in the last line we print the $common array.