Emma
Emma

Reputation: 27743

How to ignore case sensitivity and count array values?

What might be the simplest way to count array values regardless of case sensitivities?

Attempt

$arr=array("A","B","b","A","b", "a", "A");
print_r(array_count_values($arr));

or:

$arr=array("AliCE","Alice","bob","AlICE","BOB", "aLIce", "alice");
print_r(array_count_values($arr));

Demo

Current Output

Array
(
    [A] => 3
    [B] => 1
    [b] => 2
    [a] => 1
)

Desire Output

Array
(
    [A] => 4
    [B] => 2
)

Or:

Array
(
    [a] => 4
    [b] => 2
)

Upvotes: 1

Views: 802

Answers (3)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use foreach with array_key_exists and strtoupper

$arr=array("A","B","b","A","b", "a", "A");
$res = [];
foreach($arr as $k => $v){
    array_key_exists(strtoupper($v), $res) ? ($res[strtoupper($v)]++) : ($res[strtoupper($v)] = 1); 
}
print_r($res);

Working Example

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

I would use array_map but as an alternate, join into a string, change case, split into an array:

print_r(array_count_values(str_split(strtolower(implode($arr)))));

Upvotes: 1

Sash Sinha
Sash Sinha

Reputation: 22418

You can map the letters to uppercase first using strtoupper:

$arr = array("A","B","b","A","b", "a", "A");
print_r(array_count_values(array_map('strtoupper', $arr)));

Output:

(
    [A] => 4
    [B] => 3
)

Upvotes: 3

Related Questions