Re: array diff with both values returned

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Is there a good way to get the difference in two arrays and have both
values returned?  I know I can use array_dif to see what is in one and
not the other but...I need it to work a bit differently.

I have:

$array1=array("name"=>"fred","gender"=>"m","phone="=>"555-5555");
$array2=array("name"=>"fred","gender"=>"f","phone="=>"555-5555");

I want to compare these two and have it return:

array("gender"=>array("m","f"));

I want it to return all of the differences with the key and then the
value from array 1 and 2.

Well, if you can gaurantee that for every key will exist in both arrays, the following will work:


<?php

$array1=array("name"=>"fred","gender"=>"m","phone="=>"555-5555");
$array2=array("name"=>"fred","gender"=>"f","phone="=>"555-5555");

$array3 = fooFunc($array1, $array2);
print_r($array3);

function fooFunc(&$array1, &$array2) {
        foreach ( $array1 as $k1 => $v1 ) {
                $v2 = $array2[$k1];
                if ( $v1 != $v2 ) {
                        $result_ary[$k1] = array($v1, $v2);
                }
        }

        return($result_ary);
}

?>


Prints out:

% php foo.php
Array
(
    [gender] => Array
        (
            [0] => m
            [1] => f
        )

)

Depending on how large of an array you're expecting back, you might want to pass that around as a reference as well to save a copy... or not...

-philip

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux