PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

How do you hash the password in this php script: define(sb db user name, admin store); define(sb db password, mypassword);

What is the usage of { } in string handling in php?

How do I print text to the screen?

How do I reverse a string in PHP?

How do I find the ASCII value of a string character?



Custom Search