Generally, in computing, a count_chars()
is used on strings.
The count_chars()
method examines a string and identifies the individual characters using its byte-value, which is unique for every character. It will then return its evaluation on the characters of the string as indicated in a return mode value.
count_chars(string_value,mode)
string_value
: This is the string whose character will be examined.mode
: This mode parameter is an integer value. It can be 0
, 1
, 2
, 3
or 4
, which triggers a special return value. Check below for the possible return values.The value returned by this method depends on the value of the mode parameter provided. Each mode value (0
, 1
, 2
, 3
or 4
) triggers a different return value. These are discussed below:
0
: If this mode value is provided, an array value will be returned. This array is a key-value
pair array. The key
is a byte-value --that is any of the characters–. the frequency of occurrence of the byte --the character-- in the variable of concern as frequency as the value.1
: This mode value returns the same as the mode value 0
. The difference is that only byte-values with a frequency greater than zero are listed.2
: This returns the same value as mode 0
. The only difference is that only byte-values with a frequency equal to zero will be listed.3
: This mode returns a string that contains all unique characters in the provided set of characters.4
: Here, the byte-value of every available character not used in the variable provided will be returned by this mode.The count_chars()
function examines a couple of strings using some of its return modes in the code snippet below:
<?php//define variables whose character info will be returned$variable_to_count = "byte sized shots";//use foreah method to return the count of each character//in $variable_to_count1foreach (count_chars($variable_to_count, 1) as $i => $val) {echo "There is $val instance(s) of \"" , chr($i) , "\" in the string.\n";}$output1 = count_chars("The cheerleader",3);echo $output1;?>
Line 4: We declare a variable.
Lines 8–10: We start and conclude a foreach
loop that iterates the array returned by the count_chars()
function on line 8.
Line 12: We use the mode 3
of the count_chars()
method to return values of all unique characters in the string value provided.
Line 14: We print the result of the operation on line 12 to the screen.