Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_intersect

Returns the values present in every array.

Syntax

array_intersect(array $array, array ...$arrays): array

Parameters

ParameterTypeDescription
$arrayarrayThe first array.
...$arraysarrayThe 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, sql

Checking 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.

Thanks for reading!

Donate to the site — we work hard for you.