English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP count_chars() Function Usage and Example

PHP String Character Functions Manual

The count_chars() function is used to return information about the characters used in the string

Syntax

mixed count_chars ( string $string[, int $mode = 0 ] )

Definition and Usage

Used to return information about the characters used in the string

Return Value

 count_chars() returns different results based on different modes:

  • 0 - An array with all byte values as key names and counts as values.

  • 1 - Same as 0, but only lists byte values with a count greater than zero.

  • 2 - Same as 0, but only lists byte values with a count of zero.

  • 3 - Returns a string composed of all used byte values.

  • 4 - Returns a string composed of all unused byte values.

Parameter

NumberParameter and Description
1

string

The string to be counted.

2

mode

It returns the mode, please see the above return value

Online Example

In this example, we will use count_chars() to check the string, the return mode set to 1. Output the number of times different characters appear:

<?php
//Use count_chars() to check the string, the return mode set to 1. Output the number of times different characters appear

foreach (count_chars($data, 1) as $i => $val) {
   echo "The string contains \"$val\" times\", chr($i), "\" character.\n";
}
?>
Test and see ‹/›

Output result:

The string contains 4 the character " ".
The string contains 1 the character ".".
The string contains 1 the character "F".
The string contains 2 the character "T".
The string contains 1 the character "a".
The string contains 1 the character "d".
The string contains 1 the character "e".
The string contains 2 the character "n".
The string contains 2 the character "o".
The string contains 1 the character "s".
The string contains 1 the character "w".

PHP String Character Functions Manual