ekuemoah Posted September 2, 2011 Share Posted September 2, 2011 Can you explain to me why I get the following answers when I use array_diff?<?php$a1=array(2=>"Cat",1=>"Dog",2=>"Horse");$a2=array(0=>"Rat",2=>"Horse",2=>"Dog");$a3=array(0=>"Horse",1=>"Dog",2=>"Cat");print_r(array_diff_assoc($a1,$a3,$a2));?>How does the array_diff_assoc function work?Is it looking for values of the first array that are not found in any of the other arrays?Does the order in which the arrays are listed in the array_diff_assoc matter or determine which is compared first?For example, is $a1 compared to $a3 and then to $a2. The returned value is [2]="Horse". Why is this value returned and not [1]="Dog" and [2]="Horse"For a key-value pair not to be returned, the key and value pair have to be found in all arrays listed? Link to comment Share on other sites More sharing options...
boen_robot Posted September 2, 2011 Share Posted September 2, 2011 First stop, $a1 is treated as $a1=array(1=>"Dog",2=>"Horse"); and $a2 is treated as $a2=array(0=>"Rat",2=>"Dog"); because, in both cases, you've defined the key "2" twice, but only the last one is used.With that in mind... yes, the order of the inputs matters.The key 2 of $a1 is different from $a3, so that's what takes precedence over to the next comparrison, in which "Horse" is also different from "Dog", so that fails too. "Dog" is not included in the collection because the 1 key of both $a1 and $a3 is "Dog", while $a2 doesn't have that key. Link to comment Share on other sites More sharing options...
ShadowMage Posted September 2, 2011 Share Posted September 2, 2011 According to the PHP manual: Returns an array containing all the values from array1 that are not present in any of the other arrays.So any values in the first array that do not exist in any of the other arrays will be returned. But since this is the associative version of the function, keys are also compared. So instead of just values it checks if the key/value pair exists in the other arrays.EDIT: See boen_robot's reply above for an explanation of your odd results. After reading boen's I see that mine was a little off... Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.