$new_array = array_diff_key ($array1, $array2,....);
Returns all elements of $array1 which are not present in $array2 ($new_array=$array1 without $array2).... Here comparison is done based on the keys only ( NOT values ).
Comparison of two or more arrays are done by using values in array_diff()
$first=array('One' =>'First','Two'=>'Second','Three'=>'Third','Four'=>'Fourth');
$second=array('One'=> 'First','Two'=>'2nd','Third'=>'3rd','Fourth'=>'Fourth');
$result1=array_diff_key($first,$second);
while (list ($key, $val) = each ($result1)) {
echo "$key -> $val <br>";
}
Output is here.
Three -> Third
Four -> Fourth
Keys of the first index are retained. ( no re-indexing done here) <?php
$first = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$second = array('a' => 'apple', 'd' => 'date');
$third = array('b' => 'banana', 'e' => 'elderberry');
$result = array_diff_key($first, $second, $third);
print_r($result); // Output: ['c' => 'cherry']
?>
<?php
$array1 = array(1 => 'one', 2 => 'two', 3 => 'three');
$array2 = array(2 => 'two', 4 => 'four');
$result = array_diff_key($array1, $array2);
print_r($result); // Output: [1 => 'one', 3 => 'three']
?>
<?php
$array1 = array('a' => 'apple', 2 => 'banana', 'c' => 'cherry');
$array2 = array(2 => 'banana', 'b' => 'blueberry');
$result = array_diff_key($array1, $array2);
print_r($result); // Output: ['a' => 'apple', 'c' => 'cherry']
?>
<?php
$array1 = array('a' => 'apple', 'b' => 'banana');
$array2 = array();
$result = array_diff_key($array1, $array2);
print_r($result); // Output: ['a' => 'apple', 'b' => 'banana']
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.