Rohtie Posted April 17, 2008 Share Posted April 17, 2008 Is there a way to count letters in a variable and then put it in another variable. Like this: $a = 3; Where 3 is the number of a's. Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/ Share on other sites More sharing options...
djpic Posted April 17, 2008 Share Posted April 17, 2008 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 Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519604 Share on other sites More sharing options...
Rohtie Posted April 17, 2008 Author Share Posted April 17, 2008 Thank you!! I have been wondering about how to do that all day! Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519606 Share on other sites More sharing options...
jonsjava Posted April 17, 2008 Share Posted April 17, 2008 <?php $letter = array("a", "c", "d", "a", "a"); $iwant = "a"; $cwant = 0; foreach($letter as $value){ if ($value == "$iwant"){ ++$cwant; } } print $cwant; ?> Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519607 Share on other sites More sharing options...
discomatt Posted April 17, 2008 Share Posted April 17, 2008 To make it case-insensitive use this: $numinstring = substr_count( strtoupper($string), strtoupper($findletter) ); Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519610 Share on other sites More sharing options...
jonsjava Posted April 17, 2008 Share Posted April 17, 2008 wow I'm tired. I thought you said count items in an array. sorry about that. Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519611 Share on other sites More sharing options...
Barand Posted April 17, 2008 Share Posted April 17, 2008 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 ) Link to comment https://forums.phpfreaks.com/topic/101580-count-different-letters/#findComment-519811 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.