简体   繁体   中英

PHP how can I count the amount of each letter in a string with letters?

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! ;)

Use array_count_values()

$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

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"; } ?> 

Use this may be it will help you.

print_r(array_count_values(str_split("string")));

Goodluck, Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM