PHP Programming 101

March 1st, 2008

Array_diff_assoc and array_diff_key Functions

Posted by Conrad in Basic Programming, Sample Code

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)

Comments are closed.

Sorry, the comment form is closed at this time.

Bad Behavior has blocked 39 access attempts in the last 7 days.