String count chars Example
This page was last reviewed on 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.
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.
// 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 9, 2023 (new).
© 2007-2024 Sam Allen.