note 53942 modified in function.array-unique by danbrown

From: Date: Thu, 06 Nov 2008 15:07:29 +0000
Subject: note 53942 modified in function.array-unique by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146229@lists.php.net to get a copy of this message
If the array key is a string it might be important to keep it although the value is the same (as I need it at the moment). So I wrote a function which also returns array elements which have the same value but different string keys. <?php function array_unique_numeric ($arr) { $str = $int = array(); foreach(array_keys($arr) as $key) { ${(is_int($key)?'int':'str')}[$key] = $arr[$key]; } return array_merge($str, array_unique($int)); } // typical array after an array_merge()... $array = array("a" => "green", "b" => "brown", "c" => "blue", "red", "d" => "green", "yellow", "red"); print_r(array_unique($array)); // Array // ( // [a] => green // [b] => brown // [c] => blue // [0] => red // [1] => yellow // ) print_r(array_unique_numeric($array)); // Array // ( // [a] => green // [b] => brown // [c] => blue // [d] => green // [0] => red // [1] => yellow // ) ?> --was-- If the array key is a string it might be important to keep it although the value is the same (as I need it at the moment). So I wrote a function which also returns array elements which have the same value but different string keys. function array_unique_numeric ($arr) { $str = $int = array(); foreach(array_keys($arr) as $key) { ${(is_int($key)?'int':'str')}[$key] = $arr[$key]; } return array_merge($str, array_unique($int)); } // typical array after an array_merge()... $array = array("a" => "green", "b" => "brown", "c" => "blue", "red", "d" => "green", "yellow", "red"); print_r(array_unique($array)); // Array // ( // [a] => green // [b] => brown // [c] => blue // [0] => red // [1] => yellow // ) print_r(array_unique_numeric($array)); // Array // ( // [a] => green // [b] => brown // [c] => blue // [d] => green // [0] => red // [1] => yellow // ) http://php.net/manual/en/function.array-unique.php

« previous php.notes (#146229) next »