array_intersect() returns values from the first array that are present in every comparison array. Keys from the first array are preserved.
$first = ['red', 'green', 'blue'];
$second = ['green', 'blue', 'yellow'];
$result = array_intersect($first, $second);
print_r($result);Use array_intersect_assoc() when both keys and values must match.
$new_array = array_intersect ($array1, $array2,....);
$array1 : Required , the input array which will be checked. $first=array(1,2,3,4);
$second=array(1,2,3,5);
$result1=array_intersect($first,$second);
foreach ($result1 as $key => $val) {
echo "$key -> $val <br>";
}
Output is here.
0 -> 1
1 -> 2
2 -> 3
Keys of the first index are retained. ( no re-indexing done here) .
$first=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');
$second=array('One'=>1,'Two'=>2,'Third'=>3);
$result1=array_intersect_assoc($first,$second);
foreach ($result1 as $key => $val) {
echo "$key -> $val <br>";
}
Output is here.
One -> 1
Two -> 2
Three -> 3
$array1 = ["a" => "green", "b" => "red", "c" => "blue"];
$array2 = ["b" => "green", "c" => "yellow"];
$result = array_intersect($array1, $array2);
print_r($result); // Output: Array ( [a] => green )
$array1 = ["Red", "Green", "Blue"];
$array2 = ["red", "green"];
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));
print_r($result); // Output: Array ( [0] => red [1] => green )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.