Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page