Re: unexpected array_diff output
| From: | Torsten Roehr | Date: | Fri, 30 Apr 2004 09:00:16 +0000 |
| Subject: | Re: unexpected array_diff output | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-185024@lists.php.net to get a copy of this message | ||
"Frederic Noyer" <phphraban@noyer.ch> wrote in message
news:EAD71549-9A82-11D8-B06A-000A95A78AFC@noyer.ch...
> Hello there !
> I am trying to fill and then compare two arrays: one filled by a
> foreach construct, and the second by a while construct.
> I check both with a print_r to be sure that both are correctly filled
> (which seems to be the case). But then, when I try to compare them with
> a array_diff , the result is incoherent (at least to me...). I have
> tried several variant, but I don't understand what's wrong. Sure you
> guys can tell me where is my mistake.
>
> Here is the code:
>
> <?
>
> // creates first array (from a _POST[''] )
> foreach ($_POST['input_auteur'] AS $aut_ligne) {
> $part_ligne = explode(",",$aut_ligne);
> $arr1[] = (string) $part_ligne['2'];
> }
> echo "Array from POST :";
> print_r ($arr1);
>
> // creates second array (from SQL query)
> $sqlListAut = 'SELECT aut_id FROM mr_ecrit WHERE doc_id = ' .
> $_GET['docu'];
> $resultListAut = mysql_query($sqlListAut);
> while ($recListAut = mysql_fetch_array($resultListAut)) {
> $arr2[] = (string) $recListAut['aut_id'];
> }
> echo "Array from SQL:<BR>";
> print_r ($arr2);
>
> // comparing both arrays to detect if there is elements in the first
> array which are not present in the second array $result =
> array_diff($arr1, $arr2);
> echo "array_diff results :";
> print_r($result);
> ?>
>
> Here is a typical output:
> __________________________________________
> Array from POST: Array ( [0] => 2 [1] => 3 [2] => 4 )
>
> Array from SQL : Array ( [0] => 3 [1] => 4 )
> ******
> array_diff results : Array ( [0] => 2 [1] => 3 [2] => 4 )
> __________________________________________
>
> As you can see, the array_diff seems to always return all elements of
> the first array.
I think this is correct because the 3 key/value pairs from the first array
are NOT in the second one. I think the combination of key and value are
relevant for array_diff().
So if you had:
Array from POST: Array ( [0] => 2 [1] => 3 [2] => 4 )
Array from SQL : Array ( [0] => 2 [1] => 3 )
******
The diff would be:
array_diff results : Array ( [2] => 4 )
Regards, Torsten
>
> Thanks for your help.
> Best regards,
>
> Fred Noyer