Best solution for removing duplicate values ​​from case insensitive array

I found several solutions, but I can not decide which one to use. What is the most compact and efficient solution for using php array_unique() function in case insensitive array?

Example:

 $input = array('green', 'Green', 'blue', 'yellow', 'blue'); $result = array_unique($input); print_r($result); 

Result:

Array ( [0] => green [1] => Green [2] => blue [3] => yellow )

How to remove duplicate green ? Regarding deletion, we assume that the duplicates with capital letters are correct.

eg. save PHP remove PHP

or save PHP remove PHP because PHP has more uppercase characters.

Thus, the result will be

Array ( [0] => Green [1] => blue [2] => yellow )

Note that green with uppercase is saved.

+4
source share
5 answers

Will this work?

 $r = array_intersect_key($input, array_unique(array_map('strtolower', $input))); 

Does not care about a specific case to save, but does the job, you can also try calling asort($input); before crossing to save capitalized values ​​instead ( demo at IDEOne.com ).

+12
source

If you can use PHP 5.3.0, here is a function that does what you are looking for:

 <?php function array_unique_case($array) { sort($array); $tmp = array(); $callback = function ($a) use (&$tmp) { if (in_array(strtolower($a), $tmp)) return false; $tmp[] = strtolower($a); return true; }; return array_filter($array, $callback); } $input = array( 'green', 'Green', 'php', 'Php', 'PHP', 'blue', 'yellow', 'blue' ); print_r(array_unique_case($input)); ?> 

Output:

 Array ( [0] => Green [1] => PHP [3] => blue [7] => yellow ) 
+3
source
 function count_uc($str) { preg_match_all('/[AZ]/', $str, $matches); return count($matches[0]); } $input = array( 'green', 'Green', 'yelLOW', 'php', 'Php', 'PHP', 'gREEN', 'blue', 'yellow', 'bLue', 'GREen' ); $input=array_unique($input); $keys=array_flip($input); array_multisort(array_map("strtolower",$input),array_map("count_uc",$input),$keys); $keys=array_flip(array_change_key_case($keys)); $output=array_intersect_key($input,$keys); print_r( $output ); 

will return:

 Array ( [2] => yelLOW [5] => PHP [6] => gREEN [9] => bLue ) 
+1
source

First you have to make all the values ​​lowercase and then run array_unique and you are done

0
source

First, normalize your data by sending it via strtoupper() or strtolower() to make this file consistent. Then use array_unique ().

 $normalized = array_map($input, 'strtolower'); $result = array_unique($normalized); $result = array_map($result, 'ucwords'); print_r($result); 
0
source

All Articles