PHP count_chars() Function


The count_chars() function is used to returns information about the occurrences of characters in a string.

Syntax
count_chars(string,mode)
Parameters Description
string (Required) String to check.
mode (Optional) Specify the return mode. It takes values from 0 to 4 (Default is 0)
  • 0 - return an array with the ASCII as key and number of occurrences as value.
  • 1 - return an array with ASCII as keys and occurrence counts as values, but lists only occurrences greater than zero.
  • 2 - return an array with ASCII as keys and occurrence counts as values, but lists only occurrences equal to zero.
  • 3 - return a string containing all the different characters used.
  • 4 - return a string containing all unused characters.
Counting of each ASCII occurs in a string (Mode 1)
Example
<?php
  $str = "Hello World";
  $arr = count_chars($str,1);
  foreach ($arr as $k=>$v)
  {
    echo "{$k} = {$v} <br>";
  }
?>

Output

32 = 1
72 = 1
87 = 1
100 = 1
101 = 1
108 = 3
111 = 2
114 = 1
Return a string containing all the different characters used.(Mode 3)
Example
<?php
  $str = "Hello World";
  echo count_chars($str,3);
?>

Output

HWdelor
Return a string containing all unused characters.(Mode 4)
Example
<?php
  $str = "Hello World";
  echo count_chars($str,4);
?>

Output

  !"#$%&'()*+,-./0123456789:;<=>
?@ABCDEFGIJKLMNOPQRSTUVXYZ[\]^_`abcfghijkmnpqstuvwxyz{|}~��������������������������������������
������������������������������������������������������������������������������������������

Prev Next