array_diff_assoc() returns entries from the first array whose key/value pair is not present in the comparison arrays.
$first = ['a' => 'red', 'b' => 'green'];
$second = ['a' => 'red', 'b' => 'blue'];
$result = array_diff_assoc($first, $second);
print_r($result);Both the key and its value participate in the comparison.
$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).
$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);
foreach ($result1 as $key => $val) {
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.
$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);
foreach ($result1 as $key => $val) {
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);
foreach ($result2 as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
----array_diff_assoc()---
Two -> Second
Three -> Third
Four -> Fourth
----array_diff()---
Two -> Second
Three -> Third
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.