Thursday, August 22, 2013

How to compare two arrays and generate new array with common elements from both arrays in PHP?

There exists the php inbuilt function called array_intersect that computes the intersection of arrays.
 array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
//array 1: An array with master values to check.
//array 2: An array to compare values against.
//Returns an array containing all of the values in array1 whose values exist in all of the parameters.
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Example of array_intersect()
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
The above example will output:
    [a] => green
    [0] => red
In this way, you can generate array which has common elements from both arrays. :)

No comments:

Post a Comment