count_chars()

Using count_chars function we can get many information about an input string. Here is the syntax

Count_chars(string, $mode)

Default value of $mode is 0, It can take values 0 to 4. We will discuss all values but before that here is one example.

$str = "Welcome to plus2net PHP section";
$position = count_chars($str,2);
print_r($position);

Above code will return an array and by using print_r function we have displayed all keys with values of the array. The array will return all chars ( as Key of array ) and its frequency of use ( value of the key in array ) in the given string. If any char is not used then value of that key element will be zero. With different mode values ( 0 to 4) we will get returns like this

0 Returns array of all chars and its frequency of use. Not used chars also returned with zero value
1 Not used chars are not included only used chars in the string are returned with frequency of uses
2 All chars with zero value ( or all chars which are not used with zero value returned )
3 A string is returned with all used chars
4 A string is returned with all not used chars

We will try some examples here

Setting Mode to 1

By changing the mode value to 1 we will get a big list of all chars with its values. Most of them will have value as zero as we have used few chars. Here is the code

$str = " Welcome to plus2net PHP section";
$position = count_chars($str,1);
print_r($position);

The output is here

Array ( [32] => 5 [50] => 1 [72] => 1 [80] => 2 [87] => 1 [99] => 2 [101] => 4 [105] => 1 [108] => 2
[109] => 1 [110] => 2 [111] => 3 [112] => 1 [115] => 2 [116] => 3 [117] => 1 )

Let us change the mode value to 3, this is the only line to be changed.

$position = count_chars($str,3);

The output is here

2HPWceilmnopstu

Related Tutorial
Counting words
Number of occurrences
So you can see the above chars only we have used in our main string.
Interesting applications can be developed by using this function like checking the string for frequency of used chars. How many emails address are present in a string. By just checking frequency of the char @ ( char(64) we can know how many email address are included in the string. Like this many scripts can be developed. Here is the example

$str = " ron@domain.com, kris@example.com, benoy@testing.com";
$position = count_chars($str,1);
echo $position[64]; // output is 3


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    PHP String Functions

    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer