PHP count_chars() Function
Topic: PHP String ReferencePrev|Next
Description
The count_chars()
function counts the number of occurrences of an ASCII character (0..255) in a string and returns it in various ways depending on the mode.
The following table summarizes the technical details of this function.
Return Value: | Depending on the specified mode parameter. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the count_chars()
function is given with:
The following example shows the count_chars()
function in action.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Counting unique characters in the string
$arr = count_chars($str, 1);
// Iterating through returned array
foreach($arr as $i => $val){
echo "The character \"" . chr($i) . "\" occurs $val times the string.\n";
}
?>
Parameters
The count_chars()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to be examined. |
mode |
Optional. Specifies the return modes. Default is 0. The different return modes are:
|
More Examples
Here're some more examples showing how count_chars()
function actually works:
In the following example a string containing all the unique characters in the given string is returned.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Getting all unique characters in the string
echo count_chars($str, 3);
?>
In the following example an array with the ASCII values as keys, and their frequency, i.e. how many times they occurs inside the given string as values, will be returned.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Getting frequency of characters in the string
print_r(count_chars($str, 1));
?>
In the following example a string containing all not used ASCII characters in the string is returned.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Getting all unused characters in the string
echo count_chars($str, 4);
?>