Open In App

PHP array_diff_assoc() Function

Improve
Improve
Like Article
Like
Save
Share
Report

This inbuilt function of PHP is used to get the difference between one or more arrays. This function compares both the keys and values between one or more arrays and returns the difference between them. So, the function generally compares two arrays according to there keys and values and returns the elements that are present in the first array but not in other input arrays.

Note: This function is different than PHP | array_diff() function in a way that the latter only used the values to compare, but in array_diff_assoc() we use both the values and keys to compare.

Syntax:

array_diff_assoc($array1, $array2, $array3, ..., $arrayn)

Parameters: The function can take any number of arrays as parameters needed to be compared.

Return Type: This function compares the key and value of the first array of parameters with rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays.

Examples:

Input : 
$array1 = ("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI", 
                        "40"=>"KISHAN", "50"=>"RISHI")
$array2 = ("10"=>"RAM", "70"=>"LAXMAN", "30"=>"KISHAN", 
                                          "80"=>"RAGHAV")
$array3 = ("20"=>"LAXMAN", "80"=>"RAGHAV")
Output :
Array
(
    [30] => RAVI
    [40] => KISHAN
    [50] => RISHI
)

Input :
$array1 = ("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI", 
                      "40"=>"KISHAN", "50"=>"RISHI")
$array2 = ("20"=>"LAXMAN", "40"=>"RAGHAV", "40"=>"KISHAN")
Output :
Array
(
    [10] => RAM
    [30] => RAVI
    [50] => RISHI
)

Below program illustrates the working of array_diff_assoc() in PHP:




<?php
  
// PHP code to illustrate the 
// array_diff_assoc() function
  
// Input Arrays
$array1 = array("10"=>"RAM", "20"=>"LAXMAN", "30"=>"RAVI",
                            "40"=>"KISHAN", "50"=>"RISHI");
$array2 = array("10"=>"RAM", "70"=>"LAXMAN", "30"=>"KISHAN",
                                            "80"=>"RAGHAV");
$array3 = array("20"=>"LAXMAN", "80"=>"RAGHAV");
  
print_r(array_diff_assoc($array1, $array2, $array3));
  
?>


Output:

Array
(
    [30] => RAVI
    [40] => KISHAN
    [50] => RISHI
)

Reference:
http://php.net/manual/en/function.array-diff-assoc.php


Last Updated : 20 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads