note 86210 added to function.array-unique

From: Date: Wed, 08 Oct 2008 08:29:38 +0000
Subject: note 86210 added to function.array-unique
Groups: php.notes 
Request: Send a blank email to php-notes+get-145154@lists.php.net to get a copy of this message
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: <?php 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 ) ) ---- Server IP: 64.71.164.2 Probable Submitter: 75.149.61.49 ---- Manual Page -- http://www.php.net/manual/en/function.array-unique.php Edit -- https://master.php.net/note/edit/86210 Del: integrated -- https://master.php.net/note/delete/86210/integrated Del: useless -- https://master.php.net/note/delete/86210/useless Del: bad code -- https://master.php.net/note/delete/86210/bad+code Del: spam -- https://master.php.net/note/delete/86210/spam Del: non-english -- https://master.php.net/note/delete/86210/non-english Del: in docs -- https://master.php.net/note/delete/86210/in+docs Del: other reasons-- https://master.php.net/note/delete/86210 Reject -- https://master.php.net/note/reject/86210 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145154) next »