Reputation: 33
How can I count the amount of each letter in a string with letters?
For example:
$string = "ababdcbadbcabcbcadcbadbc"
Now I have to count how many a's, b's, c's and d's are in the string and I have to print the result in a diagram.
Tnx and keep programming! ;)
Upvotes: 1
Views: 175
Reputation: 1
Use this may be it will help you.
print_r(array_count_values(str_split("string")));
Goodluck, Cheers.
Upvotes: 0
Reputation: 68476
$string = "ababdcbadbcabcbcadcbadbc";
print_r(array_count_values(str_split($string)));
OUTPUT :
Array
(
[a] => 6
[b] => 8
[d] => 4
[c] => 6
)
I have to print the result in a diagram
And here comes the lovely diagram!
array_multisort($arr);
foreach($arr as $k=>$v)
{
echo str_repeat($k,$v)."<br>";
}
OUTPUT :
dddd
aaaaaa
cccccc
bbbbbbbb
See the full working demo
Upvotes: 3
Reputation: 1047
Look at this http://www.php.net/manual/en/function.count-chars.php
Hope that helps. Let me know, if not.
<?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"; } ?>
Upvotes: 2