Computer >> Computer tutorials >  >> Programming >> PHP

How does the array_diff_key() work in PHP?


It is an inbuilt function that compares the keys of one or more arrays, and returns their difference.

Syntax of the array_diff_key function

array array_diff_key($array1, $array2, ..)

The function can take two or more array names as parameters, and compares the first array with the remaining arrays.

Example

<?php
   $my_array1 = array("1"=>"Joe", "45"=>"Goldberg", "37"=>"Charolette", "91"=>"Micheal");
   $my_array2 = array("1"=>"Joe", "45"=>"Goldberg", "37"=>"Charolette");
   $my_array3 = array("1"=>"Joe", "45"=>"Goldberg");
   print_r(array_diff_assoc($my_array1, $my_array2, $my_array3));
?>

Output

Array
(
   [91] => Micheal 
)

Inside the <php> tags, three arrays are declared with certain values in them. They are printed by calling the ‘array_diff_assoc’ function by passing all the three arrays to it as parameters. The resultant value is the different between the first array, and second array as well as the difference between the first array and the third array.