PHP count_chars()function
PHP count_chars() is most important string function. It is used to return information about characters in a string.
Syntax:
count_chars(string,mode);
Parameter | Description | Required/Optional |
---|---|---|
string | The string to be checked | Required |
mode | Specify the return modes | Optiona |
- 0 : It is an array with the byte-value as key and the frequency of every byte as value.
- 1 : It is same as 0 but only byte-value with a frequency greater than zero are listed.
- 2 : same as 0 but only byte-values with a frequency equal to zero are listed.
- 4 : a string containing all not used characters is returned.
Example 1
<?php
$str = "Hello World!";
echo "Your given string: ".$str;
echo "<br>"."By using 'count_chars()' function your string is :".count_chars($str,3);
?>
Output
Your given string: Hello World!
By using 'count_chars()' function your string is : !HWdelor
Example 2
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of "" , chr($i) , "" in the string.n";
}
?>
Output
Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 )
Example 3
<?php
$str = "PHP is Lovely Language!";
$strArray = count_chars($str,1);
foreach ($strArray as $key=>$value)
{
echo "The character <br>'".chr($key)."' <br> was found $value time(s) "<br>";
}
>?
Output
The character ' ' was found 3 time(s)
The character '!' was found 1 time(s)
The character 'H' was found 1 time(s)
The character 'L' was found 2 time(s)
The character 'P' was found 2 time(s)
The character 'a' was found 2 time(s)
The character 'e' was found 2 time(s)
The character 'g' was found 2 time(s)
The character 'i' was found 1 time(s)
The character 'l' was found 1 time(s)
The character 'n' was found 1 time(s)
The character 'o' was found 1 time(s)
The character 's' was found 1 time(s)
The character 'u' was found 1 time(s)
The character 'v' was found 1 time(s)
The character 'y' was found 1 time(s)