Name

count_chars()

Synopsis

    mixed count_chars ( string str [, int mode] )

The count_chars() function takes a string parameter and returns an array containing the letters used in that string and how many times each letter was used.

Using count_chars() is complicated by the fact that it actually returns an array of exactly 255 elements by default, with each number in there evaluating to an ASCII code. You can work around this by passing a second parameter to the function. If you pass 1, only letters with a frequency greater than 0 are listed; if you pass 2, only letters with a frequency equal to 0 are listed. For example:

    $str = "This is a test, only a test, and nothing but a test.";
    $a = count_chars($str, 1);
    print_r($a);

That will output the following:

    Array ( [32] => 11 [44] => 2 [46] => 1 [84] => 1 [97] => 4 [98] => 1 [100]
    => 1 [101] => 3 [103] => 1 [104] => 2 [105] => 3 [108] => 1 [110] => 4 [111]
    => 2 [115] => 5 [116] => 8 [117] => 1 [121] => 1)

In that output, ASCII codes are used for the array keys, and the frequencies of each letter are used as the array values.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.