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

試著忘記壹切 提交于 2019-12-01 05:53:11

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).

If you can use PHP 5.3.0, here's a function that does what you're 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
)
function count_uc($str) {
  preg_match_all('/[A-Z]/', $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
)

You should first make all values lowercase, then launch array_unique and you are done

Normalize your data first by sending it through strtoupper() or strtolower() to make the case consistent. Then use your array_unique().

$normalized = array_map($input, 'strtolower');
$result = array_unique($normalized);
$result = array_map($result, 'ucwords');
print_r($result);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!