Array intersection
suggest changeThe array_intersect function will return an array of values that exist in all arrays that were passed to this function.
$array_one = ['one', 'two', 'three'];
$array_two = ['two', 'three', 'four'];
$array_three = ['two', 'three'];
$intersect = array_intersect($array_one, $array_two, $array_three);
// $intersect is [1 => 'two', 2 => 'three']
Keys from the first array are preserved. Keys from the later arrays are not used.
array_intersect() compares values only. array_intersect_assoc() also requires the keys to match.
$array_one = [1 => 'one',2 => 'two',3 => 'three'];
$array_two = [1 => 'one', 2 => 'two', 3 => 'two', 4 => 'three'];
$array_three = [1 => 'one', 2 => 'two'];
$intersect = array_intersect_assoc($array_one, $array_two, $array_three);
// $intersect contains [1 =>'one',2 => 'two']
array_intersect_key() compares keys only. It returns the entries from the first array whose keys exist in every array.
$array_one = [1 => 'one',2 => 'two',3 => 'three'];
$array_two = [1 => 'one', 2 => 'two', 3 => 'four'];
$array_three = [1 => 'one', 3 => 'five'];
$intersect = array_intersect_key($array_one, $array_two, $array_three);
// $intersect contains [1 =>'one',3 => 'three']
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents