PHP Program to check if a given letter is vowel or consonant


March 6, 2023, Learn eTutorial
3427

A vowel is a speech sound made with your mouth fairly open, the nucleus of a spoken syllable. A consonant is a sound made with your mouth fairly closed. The English alphabet has 5 vowels and 21 consonants. The below program reads an alphabet from the user and checks whether the given letter is a vowel-like a, e, i, o, u, or it is a consonant like the rest of the letters. Vowels and consonants combine to form words.

Vowel Alphabets
A, E, I, O, U, and a, e, i, o, u are the vowel Alphabets.

Consonant Alphabets
B, C, ...., Y, Z, and b, c, .., y, z are the consonant Alphabets.

check if a given letter is vowel or consonant

How to find a letter is vowel or consonant in PHP

Here in this PHP program, we use a static array vowels[ ] which holds the vowels 'a','e','i','o','u'. Now read an alphabet from the user using readLine() function in PHP and store the value in the variable letter. Then, convert the alphabet to lowercase (the user may enter capitals to check) using the built-in function strtolower($letter) and use an if condition to check the value with the elements of array vowels[ ]. If got a match then print the given alphabet as a vowel otherwise print it is as a consonant.

check if a given letter is vowel or consonant

ALGORITHM

STEP 1: Declare an array vowels[ ] and initialize it with vowels a,e, i,o,u

STEP 2: Read an alphabet to letter

STEP 3: Using the function in_array() check whether  strtolower($letter)[case of a letter converts to lowercase] in array vowels[ ], if yes then print letter is vowel else print letter is consonant.

PHP Source Code

                                          <?php
    $vowels = ['a','e','i','o','u'];
    $letter = readLine("Enter a character ");

    if (in_array(strtolower($letter), $vowels)) 
        echo $letter." is a Vowel";
     else 
        echo $letter." is a Consonant";
?>
                                      

OUTPUT

Enter a character M

M is a Consonant

Enter a character i

i is a Vowel