Count Characters Function PHP
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).