PHP: Count character occurrences in a string with count_chars

Solution:

To inspect the return value of count_chars(), you can use var_dump():


$str = "Hello World!";
var_dump(count_chars($str, 0));

✅ Explanation:

count_chars($str, 0) returns an array with the ASCII value of each character as the key and the number of occurrences as the value.

Using var_dump() lets you see both the keys and values clearly.

Example Output:


array(87) {
  [32]=> int(1)
  [33]=> int(1)
  [72]=> int(1)
  [87]=> int(1)
  [100]=> int(1)
  [101]=> int(1)
  [108]=> int(3)
  [111]=> int(2)
  [114]=> int(1)
}

This shows each character in “Hello World!” with its ASCII code and count.