Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best solution to remove duplicate values from case-insensitive array [duplicate]

I found a few solutions but I can't decide which one to use. What is the most compact and effective solution to use php's array_unique() function on a 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 do we remove the duplicate green? As far as which one to remove, we assume that duplicates with uppercase characters are correct.

e.g. keep PHP remove php

or keep PHP remove Php as PHP has more uppercase characters.

So the result will be

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

Notice that the Green with uppercase has been preserved.

like image 297
CyberJunkie Avatar asked Jun 05 '11 01:06

CyberJunkie


1 Answers

Would this work?

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

Doesn't care about the specific case to keep but does the job, you can also try to call asort($input); before the intersect to keep the capitalized values instead (demo at IDEOne.com).

like image 134
Alix Axel Avatar answered Nov 15 '22 02:11

Alix Axel