How to count the number of each vowel in a string with PHP

1 Answer

0 votes
function CountNumberOfEachVowelInString($s) {
    $vowels = "aeiou";
    $countVowels = array();
    
    foreach (str_split($vowels) as $ch) {
        $countVowels[$ch] = 0;
    }
    
    return $countVowels;
}

$s = "python c c++ c# java php javascript";
$countVowels = CountNumberOfEachVowelInString($s);

foreach (str_split($s) as $ch) {
    if (array_key_exists($ch, $countVowels)) {
        $countVowels[$ch]++;
    }
}

print_r($countVowels);



/*
run:

Array
(
    [a] => 4
    [e] => 0
    [i] => 1
    [o] => 1
    [u] => 0
)

*/

 



answered Jul 16, 2024 by avibootz

Related questions

1 answer 123 views
1 answer 112 views
1 answer 103 views
1 answer 93 views
1 answer 119 views
...