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
// 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
Contact Us