PHP Formatter

A Unique Blog about PHP

Array_diff_assoc and array_diff_key Functions

The next array comparison functions is the array_diff_assoc(array1,array2,array3,array3…..), usage is similar with all of these array_diff functions varying only in the way the comparisons are done. Below is sample code for array_diff_assoc:

$a1=array(0=>“Mouse”,1=>”Cat”,2=>”Dog”); $a2=array(0=>”Lizard”,1=>”Dog”,2=>”Cat”); $a3=array(0=>”Dog”,1=>”Cat”,2=>”Mouse”); print_r(array_diff_assoc($a1,$a2,$a3)) ?>

Giving you : Array ([0] => Mouse [2] => Dog).

Next we have the array_diff_key() function compares two or more arrays and returns an array with the keys and values from the first array only if the key is not present in the other arrays. Syntax is array_diff_key(array1,array2,array3……)which is similar to the other array_diff functions.

Sample usage:

$a1=array(0=>“Mouse”,1=>”Cat”,2=>”Dog”); $a2=array(2=>”Fish”,3=>”Rat”,4=>”Bee”); $a3=array(5=>”Dog”,6=>”Cat”,7=>”Fish”) print_r(array_diff_key($a1,$a2,$a3)); ?>

Giving you : Array([0] => Mouse [0] => Cat)