Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - If a string or variable begins with a vowel

I did a if thing to check if the variable only had aplha caracter but I also want to check if the variable strated with a vowel.

if (ctype_alpha($original)) {
        print "oké";
    }
    else {
        print "pas oké";
    }

If there isn't any specific function, how could I know ? Thank you

like image 623
nicobld Avatar asked Sep 02 '26 13:09

nicobld


1 Answers

$vocals = array('a','e','i','o','u');

if (ctype_alpha($original) && in_array($original{0}, $vocals)) {
  print "oké";
} else {
  print "pas oké";
}

With $string{index} you could access to a char into a certain position into $string.

With in_array you could check if that letter is contained into an array (in our example, vocals array)


Alternative solution

If you wish, you could even use preg_match that will perform test with regular expressions

if (ctype_alpha($original) && preg_match('/^[aeiou]/i', $original))
like image 73
DonCallisto Avatar answered Sep 05 '26 03:09

DonCallisto