array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'uk', ), 'this' => array ( 0 => 'function.array-diff.php', 1 => 'array_diff', 2 => 'Computes the difference of arrays', ), 'up' => array ( 0 => 'ref.array.php', 1 => 'Функції для роботи з масивами', ), 'prev' => array ( 0 => 'function.array-count-values.php', 1 => 'array_count_values', ), 'next' => array ( 0 => 'function.array-diff-assoc.php', 1 => 'array_diff_assoc', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'reference/array/functions/array-diff.xml', ), 'history' => array ( ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); contributors($setup); ?>
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_diff — Computes the difference of arrays
Compares array
against one or more other arrays and
returns the values in array
that are not present in
any of the other arrays.
array
The array to compare from
arrays
Arrays to compare against
Returns an array containing all the entries from
array
that are not present in any of the other arrays.
Keys in the array
array are preserved.
Версія | Опис |
---|---|
8.0.0 | Тепер ця функція може викликатись лише з одним параметром. Раніше потрібні були щонайменше два. |
Приклад #1 array_diff() example
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Multiple occurrences in $array1 are all treated the same way. This will output :
Array ( [1] => blue )
Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2
. That is,
when the string representation is the same.
Приклад #2 array_diff() example with non-matching types
<?php
// This will generate a Notice that an array cannot be cast to a string.
$source = [1, 2, 3, 4];
$filter = [3, 4, [5], 6];
$result = array_diff($source, $filter);
// Whereas this is fine, since the objects can cast to a string.
class S {
private $v;
public function __construct(string $v) {
$this->v = $v;
}
public function __toString() {
return $this->v;
}
}
$source = [new S('a'), new S('b'), new S('c')];
$filter = [new S('b'), new S('c'), new S('d')];
$result = array_diff($source, $filter);
// $result now contains one instance of S('a');
var_dump($result);
?>
To use an alternate comparison function, see array_udiff().
Зауваження:
This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using
array_diff($array1[0], $array2[0]);
.