Saturday, July 3, 2010

Unique value in array.. i.e. in nested array

I came across one limitation of array_unique: it doesn't work properly if you have arrays inside your main array.

The reason is that to compare two values, the function tests if (string) $value1 == (string) $value2. So if $value1 and $value2 are both arrays, the function will evaluate the test to 'Array' == 'Array', and decide that the $values are repeated even if the arrays are different.

So a work around is to find a better conversion of an array to a string, which can be done with json:

print "define an array with repeated scalar '1' and repeated 'array(1)':";
$a_not_unique = array(
   
'a' => 1,
   
'b' => 1,
   
'c' => 2,
   
'd' => array(1),
   
'e' => array(1),
   
'f' => array(2),
);
print_r($a_not_unique);

print
"try to use simply array_unique, which will not work since it exludes 'array(2)':";
$a_unique_wrong = array_unique($a_not_unique);
print_r($a_unique_wrong);

print
"convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':";
$a_unique_right = $a_not_unique;
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_encode($value);'));
$a_unique_right = array_unique($a_unique_right);
array_walk($a_unique_right, create_function('&$value,$key', '$value = json_decode($value, true);'));
print_r($a_unique_right);
?>

Results:
define an array with repeated scalar '1' and repeated 'array(1)':
Array
(
    [a] => 1
    [b] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [e] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)

try to use simply array_unique, which will not work since it exludes 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )
)

convert to json before applying array_unique, and convert back to array, which will successfully keep 'array(2)':
Array
(
    [a] => 1
    [c] => 2
    [d] => Array
        (
            [0] => 1
        )

    [f] => Array
        (
            [0] => 2
        )
)

No comments: