The array_diff_assoc Function

The array_diff_assoc function compares arrays and returns elements from the first array that are not present in the subsequent arrays, taking into account both keys and values. It uses strict comparison (===) for the comparison.

Syntax

phparray_diff_assoc(array $array1, array $array2, array ...$arrays): array

Example

Let's compare two arrays with different keys and values:

php<?php
  $arr1 = ['a' => 1, 'b' => 2, 'c' => 3];
  $arr2 = ['a' => 1, 'b' => 5, 'd' => 4];
  
  $res = array_diff_assoc($arr1, $arr2);
  print_r($res);
?>

Code execution result:

php['b' => 2, 'c' => 3]

Example

Comparison of three arrays with numeric keys:

php<?php
  $arr1 = [1, 2, 3, 4];
  $arr2 = [1, 3, 3, 4];
  $arr3 = [1, 2, 3, 5];
  
  $res = array_diff_assoc($arr1, $arr2, $arr3);
  print_r($res);
?>

Code execution result:

php[1 => 2]

Example

Comparison with different data types:

php<?php
  $arr1 = ['a' => '1', 'b' => 2];
  $arr2 = ['a' => 1, 'b' => '2'];
  
  $res = array_diff_assoc($arr1, $arr2);
  print_r($res);
?>

Code execution result:

php['a' => '1', 'b' => 2]

See Also

  • the array_diff function,
    which compares arrays by values without taking keys into account
  • the array_intersect_assoc function,
    which finds the intersection of arrays with keys taken into account