Hướng dẫn
Quảng cáo

Hàm array_diff_key() trong PHP

Hướng dẫn cách sử dụng hàm array_diff_key() về mảng trong lập trình PHP

Tác dụng của hàm array_diff_key()

The array_diff_key() function compares the keys of two or more arrays and returns the differences.

Also, the values for the keys are not considered in the comparison, only the keys are checked.

The following table summarizes the technical details of this function.

Return Value: Returns an array containing all the elements from array1 whose keys are not present in any of the other arrays.
Version: PHP 5.1.0+

Syntax

The basic syntax of the array_diff_key() function is given with:

array_diff_key(array1, array2, ...);

The following example shows the array_diff_key() function in action.

<?php
// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "dog");
$array2 = array("a"=>"apricot", "b"=>"banana");

// Computing the difference
$result = array_diff_key($array1, $array2);
print_r($result);
?>

Parameters

The array_diff_key() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array to compare from.
array2 Required. Specifies an array to compare against.
... Optional. Specifies more arrays to compare against.

More Examples

Here're some more examples showing how array_diff_key() function actually works:

In the following example this function compares an array against two other arrays.

<?php
// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "dog");
$array2 = array("a"=>"apricot", "b"=>"banana");
$array3 = array("a"=>"alligator", "d"=>"dog");

// Computing the difference
$result = array_diff_key($array1, $array2, $array3);
print_r($result);
?>

The two keys from the key=>value pairs are considered equal if their string representation are same, i.e., (string) $key1 === (string) $key2. Let's try out the following example:

<?php
// Sample arrays
$array1 = array(1, 2, 5, 7, 10);
$array2 = array(0, "1"=>3, "x"=>8, "4"=>13);

// Computing the difference
$result = array_diff_key($array1, $array2);
print_r($result);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements