Skip to content
Related Articles

Related Articles

PHP | count_chars() Function
  • Last Updated : 21 Nov, 2019

The count_chars() is an inbuilt function in PHP and is used to perform several operations related to string like the number of an ASCII character occurs in a string.

Syntax :

count_chars(string,return_mode);

Parameters: The count_chars() function takes two parameters string and return_mode as explained below:

  • string : This parameter refers to the input string on which the operation is to be performed.
  • return_mode : This parameter is optional. This parameter defines the operation needed to be performed on the string. It takes value 0, 1, 2, 3, 4.

    1. 0 : If this mode is chosen, the function will return an array with key-value pairs whose keys are ASCII values and the corresponding values will be the number of occurrences of that ASCII value.
    2. 1 : If this mode is chosen, the count_chars() function will return an array with key-value pairs whose keys are ASCII values and the corresponding values will be the number of occurrences of that ASCII value . Here, the array will contain only those keys as ASCII values whose frequency is greater than 0.
    3. 2 : In this mode, the function will return an array of key-value pairs where key are the ASCII value whose frequency in the string is 0.
    4. 3 : In this mode the count_chars() function will return a string of all different characters used in the string in ascending order.
    5. 4 : In this mode the count_chars() function will return a string of characters that are not used in input string

Return Type: This function will return an array or string depending on the parameter return_mode as described above.



Examples:

Input : string = "GeeksforGeeks"  ,  return_mode = 3
Output : Gefkors

Below is the PHP program to illustrate the working of count_chars() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
    // PHP program to illustrate count_chars() 
      
    // Input string
    $string = "geeksforgeeks";
  
    // return_mode 1
    print_r(count_chars($string,1));
  
    // return_mode 3
    print_r(count_chars($string,3));
  
    // return_mode 4
    print_r(count_chars($string,4));
?>

chevron_right


Output:

Array
(
    [101] => 4
    [102] => 1
    [103] => 2
    [107] => 2
    [111] => 1
    [114] => 1
    [115] => 2
)

efgkors

!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXY
Z[\]^_`abcdhijlmnpqtuvwxyz{|}~??????????????????????
????? ¡¢£¤¥¦§¨©ª«¬­®¯´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×
ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

The above program shows the return values for string “geeksforgeeks” with return_mode as 1, 3 and 4. You can modify the program by changing the value of return_mode in the function call to see the returned values for modes 0 and 2 also.

My Personal Notes arrow_drop_up
Recommended Articles
Page :