array_diff_key(): Difference between two arrays with respect to Keys

This function takes two or more arrays as input and then returns the result array as difference.
$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()

Example with two arrays

$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)

Example 1: Comparing Three Arrays

<?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']
?>

Example 2: Using Numeric Keys

<?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']
?>

Example 3: Mixed Key Types in Arrays

<?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']
?>

Example 4: Comparing with an Empty Array

<?php
$array1 = array('a' => 'apple', 'b' => 'banana');
$array2 = array();
$result = array_diff_key($array1, $array2);
print_r($result);  // Output: ['a' => 'apple', 'b' => 'banana']
?>

Joining Two Arrays by array_merge
Array REFERENCE
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer