Monday, 13 August 2018

How to Find/get Common Values from Multiple Arrays using PHP?

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.
1
2
3
4
5
<?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-
1
2
3
4
5
6
7
8
9
<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>
Output:
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.

0 comments:

Post a Comment