array_diff_assoc(): Difference between two arrays considering keys

This function takes two or more arrays as input and then returns the result array as difference.
$new_array = array_diff_assoc ($array1, $array2,....);
Returns all elements of $array1 which are not present in $array2 considering keys also($new_array=$array1 without $array2).

Example with two arrays

$first=array('One' =>'First','Two'=>'Second','Three'=>'Third','Four'=>'Fourth');
$second=array('One'=> 'First','Two'=>'2nd','Third'=>'3rd','Fourth'=>'Fourth');

// What is not common in both arrays ( keys also considered ) ///
$result1=array_diff_assoc($first,$second);
while (list ($key, $val) = each ($result1)) {
echo "$key -> $val <br>";
}
Output is here.
Two -> Second 
Three -> Third 
Four -> Fourth 
Keys of the first index are retained. ( no re-indexing done here) . The last element of $first array is included in output as the index or key is not matching with $second array though the value is matching.

Difference between array_diff() and array_diff_assoc()

We can check the above example by using array_diff() and array_diff_assoc()
$first=array('One' =>'First','Two'=>'Second','Three'=>'Third','Four'=>'Fourth');
$second=array('One'=> 'First','Two'=>'2nd','Third'=>'3rd','Fourth'=>'Fourth');

// What is not common in both arrays ( keys also considered ) ///
echo "<br>----array_diff_assoc()---<br>";
$result1=array_diff_assoc($first,$second);
while (list ($key, $val) = each ($result1)) {
echo "$key -> $val <br>";
}

// What is not common in both arrays ( without considering Keys ) ///
echo "<br>----array_diff()---<br><br>";
$result2=array_diff($first,$second);
while (list ($key, $val) = each ($result2)) {
echo "$key -> $val <br>";
}
Output is here
----array_diff_assoc()---
Two -> Second 
Three -> Third 
Four -> Fourth 

----array_diff()---

Two -> Second 
Three -> Third 

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