How to use array_diff_key() Function In PHP

The array_diff_key() function compares the keys of two (or more) arrays and returns an array containing the key-value pairs from the first array that have keys not present in any of the other arrays.

Example: The array_diff_key() function compares the keys of $arr1 and $arr2 and returns an array containing the key-value pairs from $arr1 that have keys not present in $arr2.

PHP
<?php

// Declare two associative arrays
$arr1 = [
    1 => "one", 
    2 => "two", 
    3 => "three"
];

$arr2 = [
    3 => "three", 
    4 => "four", 
    5 => "five"
];

$diff = array_diff_key($arr1, $arr2);
print_r($diff);

?>

Output
Array
(
    [1] => one
    [2] => two
)

How to get the Difference Between Two Arrays in PHP?

Given two Arrays, the task is to get the difference between two arrays in PHP. To get the difference between two arrays, compare both arrays and retrieve values that are present in the first array but not in the second array.

Below are the approaches to get the difference between two arrays in PHP:

Table of Content

  • Using array_diff() Function
  • Using array_diff_assoc() Function
  • Using array_udiff() Function
  • Using array_diff_key() Function

Similar Reads

Using array_diff() Function

The array_diff() function compares the values of two (or more) arrays and returns an array containing the values from the first array that are not present in any of the other arrays....

Using array_diff_assoc() Function

The array_diff_assoc() function compares both the keys and values of two (or more) arrays and returns an array containing the values from the first array that are not present in any of the other arrays....

Using array_udiff() Function

The array_udiff() function compares the values of two (or more) arrays using a user-defined comparison function and returns an array containing the values from the first array that are not present in any of the other arrays....

Using array_diff_key() Function

The array_diff_key() function compares the keys of two (or more) arrays and returns an array containing the key-value pairs from the first array that have keys not present in any of the other arrays....

Contact Us