Science Stream Practicals

Std 12th IT Subject - Skill Oriented Practical (Science Stream)

SOP 2: Write a PHP function to count the total number of vowels from the string.

Write a PHP function to count the total number of vowels (a,e,i,o,u) from the string.
Accept a string by using HTML form.

Source Code: SOP.php

<!DOCTYPE html>
<html>
<head>
    <title>Count Vowels in String</title>
</head>
<body>
    <h2>PHP program to check number of vowels in a string</h2>
    <form method="post" action="">
        Enter a string: <input type="text" name="String" required>
        <input type="submit" value="Count Vowels">
    </form>

    <?php
    function countVowels($str) {
        $str = strtolower($str);
        $count = 0;
        for ($i = 0; $i < strlen($str); $i++) {
            $ch = $str[$i];
            if ($ch == 'a' || $ch == 'e' || $ch == 'i' || $ch == 'o' || $ch == 'u') {
                $count++;
            }
        }
        echo "<p>Number of vowels in string are: " . $count . "</p>";
    }
    if (isset($_POST["String"])) {
        countVowels($_POST["String"]);        
    }
    ?>
</body>
</html>

Live Preview