array_intersect
Returns the values present in every array.
Syntax
array_intersect(array $array, array ...$arrays): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The first array. |
| ...$arrays | array | The arrays to compare against. |
Return value
arrayThe common values.
Examples
Shared interests:
<?php
$anna = ['php', 'sql', 'css'];
$oleg = ['js', 'sql', 'php'];
echo implode(', ', array_intersect($anna, $oleg));Output:
php, sqlChecking that only allowed values were chosen:
<?php
$allowed = ['red', 'green', 'blue'];
$chosen = ['red', 'black'];
var_dump(count(array_intersect($chosen, $allowed)) === count($chosen));Output:
bool(false)Notes
The keys and the order come from the first array.
See also
- array_diff — Returns the values of the first array that are absent from the others.
- in_array — Checks whether a value exists in an array.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.