count the occurrences of all the letters in a string PHP
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتکنفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسالهاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسیبیاسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبینالمللیخودادامهمیدادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانهسرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
You don't have to convert that into an array()
you can use substr_count()
to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count()
returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars
to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string