Skip to content

How can I find matching values in two arrays in PHP?

  • by
php-arrays

This tutorial explains how can i find matching values in two arrays in php. I have kept this article very simple so that anyone can implement on their web page.

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

This builtin function of PHP is used to compute the intersection of two or more arrays. The function is used to compare the values of two or more arrays and returns the matches. The function prints only those elements of the first array that are present in all other arrays.

Syntax : array_intersect()

array array_intersect($array1, $array2, $array3, $array4...)

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

Parameters: The array with master values to check.

Arrays to compare values against

Return Type: Returns an array containing all of the values in array whose values exist in all of the parameters.

Examples


<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
)

A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

Good luck and I hope this article can be useful. See you in the next article…

If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!

Leave a Reply

Your email address will not be published. Required fields are marked *