PHP Function Reference

PHP count_chars() Function



The PHP count_chars() function returns the information about characters used in a string. It performs several operations on a string like counting the number of times an ASCII character occurs in a string.

Syntax

count_chars(string, mode)

Parameters

string Required. Specify the string to be checked.
mode Optional. Specify the mode. Default mode is 0. Depending on mode the function returns the following:
  • 0 - an array with ASCII value as key and number of occurrences as value.
  • 1 - an array with ASCII value as key and number of occurrences as value, only lists occurrences greater than zero.
  • 2 - an array with ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed.
  • 3 - a string with all the different characters used.
  • 4 - a string with all the unused characters.

Return Value

Returns an array or string depending on the specified mode.

Example:

The example below demonstrates the usage of count_chars() function.

<?php
$str = "AlphaCodingSkills";

//using mode 1
print_r(count_chars($str, 1));

echo "\n";

//using mode 3
print_r(count_chars($str, 3));
?>

The output of the above code will be:

Array
(
    [65] => 1
    [67] => 1
    [83] => 1
    [97] => 1
    [100] => 1
    [103] => 1
    [104] => 1
    [105] => 2
    [107] => 1
    [108] => 3
    [110] => 1
    [111] => 1
    [112] => 1
    [115] => 1
)

ACSadghiklnops

❮ PHP String Reference