In this tutorial, you shall learn about PHP array_diff_assoc() function which can compute the difference of an array against other arrays, with syntax and examples.

PHP array_diff_assoc() Function

PHP array_diff_assoc() function computes the difference of an array against other arrays. Both key/index and value are considered for comparison.

In this tutorial, we will learn the syntax of array_diff_assoc(), and how to use this function to find the difference of an array from other arrays, covering different scenarios based on array type and arguments.

Syntax of array_diff_assoc()

The syntax of PHP array_diff_assoc() function is

</>
Copy
array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) : array

where

ParameterDescription
array1[mandatory] Array of interest. Compare the items of this array against other arrays’.
array2[mandatory] Array of reference. The items of this array are used to comparison against.

Along with array2, you can provide as many number of arrays to compare against. But these additional arrays are optional.

Return Value

The array_diff_assoc() function returns an array whose key-value pairs are present in $array1 but not present in $array2 or other arrays(if provided).

Examples

1. Compute difference of Arrays: array1 – array2

In this example, we will take an associative array, array1, with key-value pairs, and compare it against another array, array2.

PHP Program

</>
Copy
<?php
$array1 = array('a'=>'apple', 'b'=>'banana', 'c'=>'cherry');
$array2 = array('a'=>'apricot', 'b1'=>'banana', 'c'=>'cherry');
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Output