Answer to Question #118492 in Web Development for Kartikeya

Question #118492
Write a PHP script to accept a string from the user and display the total number of vowels in the string. Also show the number of occurrences of each vowel in the string. (Do not use in-built function for counting vowels.)
1
Expert's answer
2020-05-31T15:58:43-0400
$str = readline('Enter string: ');
$str = strtolower($str);

$vowels = 'aeiou';
$vowelsTotal = 0;
$vowelsMap = array();

for ($i = 0; $i < strlen($str); $i++) {
  $char = $str[$i];
  
  // check if current char is vowel
  if (strpos($vowels, $char)) {

    // increase total number
    $vowelsTotal++;

    // increase number of each vowel
    if (array_key_exists($char, $vowelsMap)) {
      $vowelsMap[$char]++;
    } else {
      $vowelsMap[$char] = 1;
    }
  }
}

echo 'Total vowels: ' . $vowelsTotal . PHP_EOL;

echo 'Occurrences: ' . PHP_EOL;
foreach($vowelsMap as $key => $val) {
  echo ' ' . $key . ' - ' . $val . PHP_EOL;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS