Home
PHP
String count chars Example
Updated Jun 9, 2023
Dot Net Perls
Count chars. Suppose we want to find the most common letter in a string. We could do this with the built-in count_chars function in PHP.
When we pass this function a string, it returns an array of frequencies. Each letter is indexed as the key, and each count of instances is the value.
array
Example. The count_chars function can be used in a variety of ways. We can access indexes directly, or use a foreach loop to iterate and test.
Step 1 To begin we use a string that has 2 letter "A" chars, 3 lowercase "b" chars and some other values.
Step 2 We invoke the count_chars function and pass the string literal we just described to it.
Step 3 We can access the counts of characters directly with indexes. We use ord() to get an int from a char to use here.
Step 4 If a char was not found in the string, its count value is equal to 0. The question mark was not found.
Step 5 It is possible to iterate with a foreach-loop over the count array. If a value was not zero, we print it with echo.
foreach
// Step 1: use this string. $test = "AAbbbcccc."; // Step 2: call count chars. $counts = count_chars($test); // Step 3: print some counts that exist. echo $counts[ord('A')], "\n"; echo $counts[ord('b')], "\n"; echo $counts[ord('c')], "\n"; // Step 4: if a value does not exist, it is empty. echo $counts[ord('?')], "\n"; // Step 5: loop over all elements in the returned array. // Print the ones that have 1 or more count. foreach ($counts as $key => $value) { if ($value != 0) { echo "Key exists: " . chr($key) . " = " . $value . "\n"; } }
2 3 4 0 Key exists: . = 1 Key exists: A = 2 Key exists: b = 3 Key exists: c = 4
Some programming tasks in PHP are done with a custom function and for-loops. But with a built-in function like count_chars, we can sometimes reduce code and make programs simpler.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 9, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen