Jump to content

Count different letters


Rohtie

Recommended Posts

Yes, vary easy.

<?
$string = "Hello, I am looking for how many A's there are in this string";
$findletter = "a";
$numinstring = substr_count($string, $findletter); ?>

 

I believe that case does matter.

 

See:

http://us2.php.net/manual/en/function.substr-count.php

 

If you want counts of all the letters in the string

<?php 
$str = 'abcabcdefdedababaa';
$arr = str_split($str);
$count = array_count_values($arr);
echo '<pre>', print_r($count, true), '</pre>';

/*
-->
Array
(
    [a] => 6
    [b] => 4
    [c] => 2
    [d] => 3
    [e] => 2
    [f] => 1
)
*/

echo $count['a'] ;         // 6      
echo $count['d'] ;         // 3      

?>

 

Or you could use count_chars($str, 1) but that gives an array indexed by ascii values

Array
(
    [97] => 6
    [98] => 4
    [99] => 2
    [100] => 3
    [101] => 2
    [102] => 1
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.