PHP array_intersect() Function
In this chapter you will learn:
- Definition for PHP array_intersect() Function
- Syntax for PHP array_intersect() Function
- Parameter for PHP array_intersect() Function
- Example - Merge indexed array
- Example - merge keys during intersect
Definition
The array_intersect()
function returns a new array containing all the values of array
$arr1
that exist in array $arr2
.
You can intersect several arrays simultaneously by providing more parameters to the function. For example:
$arr1_shared = array_intersect($arr1, $arr2, $arr3, $arr4);
Syntax
PHP array_intersect() Function has the following syntax.
array array_intersect ( array arr1, array arr2 [, array ...] )
Parameter
Parameter | Is Required | Description |
---|---|---|
array1 | Required. | Array to compare from |
array2 | Required. | Array to compare against |
array3,... | Optional. | Arrays to compare against |
Example 1
<?PHP//from ja v a 2 s .c o m
$toppings1 = array("A", "B", "C", "java2s.com");
$toppings2 = array("C", "java2s.com", "D");
$int_toppings = array_intersect($toppings1, $toppings2);
var_dump($int_toppings);
?>
The code above generates the following result.
Example 2
The array_intersect()
function will try to retain array keys when possible.
For example, if you are intersecting two arrays that have no duplicate keys, all the keys will
be retained. However, if there are key clashes, array_intersect()
will use the first
array to contain it. For example:
<?PHP//from j a v a 2s. c o m
$arr1 = array("A"=>25, "B"=>38, "C"=>27);
$arr2 = array("B"=>99, "D"=>38);
var_dump(array_intersect($arr1, $arr2));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_intersect_assoc() Function
- Syntax for PHP array_intersect_assoc() Function
- Parameter for PHP array_intersect_assoc() Function
- Return for PHP array_intersect_assoc() Function
- Example - Compare the keys and values of two arrays, and return the matches
- Example - Compare the keys and values of three arrays, and return the matches
Home » PHP Tutorial » PHP Array Functions