检查元素是否是没有正则表达式的数组中的元音

检查元素是否是没有正则表达式的数组中的元音

问题描述:

Is there a better way to check if an element is a vowel in an array?

foreach($alphaArray as $alpha) {
    $ascii = ord($alpha); // convert each alpha to ascii

    if($ascii == 65 || $ascii == 69 || $ascii == 73 || $ascii == 79 || $ascii == 85
        || $ascii == 97 || $ascii == 101 || $ascii == 105 || $ascii == 111 || $ascii == 117) {
        $vowelArray[] = $alpha;

    } else {
        $consonantArray[] = $alpha;
    }
}

Teacher does not allow regEx.

有没有更好的方法来检查元素是否是数组中的元音? p> \ n

  foreach($ alphaArray as $ alpha){
 $ ascii = ord($ alpha);  //将每个alpha转换为ascii 
 
 if($ ascii == 65 || $ ascii == 69 || $ ascii == 73 || $ ascii == 79 || $ ascii == 85 
 ||  $ ascii == 97 || $ ascii == 101 || $ ascii == 105 || $ ascii == 111 || $ ascii == 117){
 $ vowelArray [] = $ alpha; 
 
}  else {
 $ consonantArray [] = $ alpha; 
} 
} 
  code>  pre> 
 
 

教师不允许使用regEx。 p> div >

This should work for you:

(Here i just use in_array() and strtouppper() to check if it is a vowel)

$vowels = array('A', 'E', 'I', 'O', 'U');

foreach($alphaArray as $alpha) {

    if(in_array(strtoupper($alpha), $vowels)) {
        $vowelArray[] = $alpha;
    } else {
        $consonantArray[] = $alpha;
    }

}

Try with -

$vowels = array('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U');
foreach($alphaArray as $alpha) {
    if(in_array($alpha, $vowels, true)) {
        $vowelArray[] = $alpha;
    } else {
        $consonantArray[] = $alpha;
    }
}

Try using strtolower and loop the array over alphabets: strtolower will convert capital letters to small.

 foreach($alphaArray as $alpha) {
        $ascii = strtolower($alpha); // convert each alpha to ascii

        if($ascii == 'a' || $ascii == 'e' || $ascii == 'i' || $ascii == 'o' || $ascii == 'u') {
            $vowelArray[] = $alpha;

        } else {
            $consonantArray[] = $alpha;
        }

}