String Functions
Advertisements

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:

count_chars(string, mode);

The following example shows the count_chars() function in action.

<?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:

  • 0 - an array with the ASCII value as key and number of occurrences as value.
  • 1 - same as 0 but only ASCII values with the occurrences greater than zero are listed.
  • 2 - same as 0 but only ASCII values with the occurrences equal to zero are listed.
  • 3 - a string containing all unique characters is returned.
  • 4 - a string containing all the unused characters is returned.

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.

<?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.

<?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.

<?php
// Sample string
$str = "Hello World!";

// Getting all unused characters in the string
echo count_chars($str, 4);
?>
Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties