Count
charsSuppose 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.
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.
string
that has 2 letter "A" chars, 3 lowercase "b" chars and some other values.count_chars
function and pass the string
literal we just described to it.ord()
to get an int
from a char
to use here.char
was not found in the string, its count value is equal to 0. The question mark was not found.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.