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 

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




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