PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I count how many times each character occurs in a string?


This might not be something that you need every day and probably not when beginning PHP, but nevertheless there are uses for such a check.

And it's best to use the built in function rather than cobble together a function yourself, although it wouldn't be too hard to write.

Let the function count_chars() take the strain. Here we see how this nifty little function lets us effortly count how many times each character occurs within a string of text:

<?php
$mytext 
"Always use a function";
$arrayofinfo count_chars($mytext,1);
//this returns an array which we explore thus:
foreach($arrayofinfo as $key => $value) {
print 
"$key occurs $value times\n";
}
//this gives us the byte value of key so the data we get is like this: 32 occurs 3 times, so we need to pass through chr($key) to get this:

foreach($arrayofinfo as $key => $value) {
print 
"'" chr($key) . "' occurs $value times\n";
}

?>


...we now get our desired output:

' ' occurs 3 times
'A' occurs 1 times
'a' occurs 2 times
'c' occurs 1 times
'e' occurs 1 times
'f' occurs 1 times
'i' occurs 1 times
'l' occurs 1 times
'n' occurs 2 times
'o' occurs 1 times
's' occurs 2 times
't' occurs 1 times
'u' occurs 2 times
'w' occurs 1 times
'y' occurs 1 times



More strings PHP Questions

How can I remove trailing space from a string?
How do I make the first letter of a string uppercase?
How do I check if a string contains HTML?
How do I remove space from the start of a PHP string?
What is the difference between print and echo?