Count Characters Function PHP As part of studying algorithms, I needed to make a function to count occurrences of characters in a string. My solution is below. I'd like some feedback about how I did - could the implementation be cleaner? Are there any conceptual gaps my code suggests?

&lt;?php
function ra_count_chars($str){
    $dict = str_split(strtolower(str_replace(' ', '', $str)));

    foreach($dict as $key=&gt;$value){
        $dict[$value] = 0;
        unset($dict[$key]);
    }

    for($i = 0; $i &lt; strlen($str); $i++){
        $dict[$str[$i]] += 1;
    }

    return $dict;
}

print_r(ra_count_chars('ccaaat'));
You can do it with a more reduced code, taking advantage of the PHP count_chars() function:

function ra_count_chars($str) {
    foreach (count_chars(str_replace(' ', '', $str), 1) as $char =&gt; $count) {
        $result[chr($char)] = $count;
    }
    return $result;
}


This method has pros and cons:


pro: the characters are alphabetically sorted in $result
pro or con (depends on your need): upper- and lower-case are counted separately


In the other hand, as noticed by @insertusernamehere, this doesn't work for multibyte characters.

Last point: due to the above limitation, you might choose to omit not only spaces but also any character other than A-Z and a-z.
To achieve it merely change str_replace(' ', '', $str) into preg_replace('/[^A-za-z]/', '', $str).