1

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

3 Answers 3

3

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't see mario's comment until after I came back to the question. I had opened a PHP console in another tab.
@JedLynch I feel ya happened today to me for a couple of python questions by like literally seconds.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.