I want to take a random string of the array and should count the consonants of the random string.
Problem is it did not count the letters from array_rand().
Here is what I get at this point:
$woerter = [
"Maus",
"Automobil",
"Schifffahrt",
"Hund",
"Katze",
"Ziege",
"Stanniolpapier",
"Elefant",
"Isopropylalkohol",
"Schwimmbad"
];
$random = array_rand($woerter);
$konsonanten = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","u","v","w","x","y","z",
"B","C","D","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z"];
$zaehler = 0;
if (in_array($woerter[$random], $konsonanten)) {
$zaehler++;
}
echo "Das Wort "$woerter[$random]" enthält $zaehler Zeichen, die keine Vokale sind.";
2
Answers
You’re testing whether the whole word is in the array of consonants, not counting each character. You need to loop over the characters.
Writing out a full array of whitelisted consonants seems more tedious that I’d prefer to code. Making looped calls of
in_array()
on each character doesn’t feel clever/efficient to me either.Consider merely stripping out all vowels, then counting what is left. Mind you, if your words might have multibyte/accented characters, you’ll need to accommodate that possibility too.
mb_strlen()
might be necessary as well (instead ofstrlen()
).Code: (Demo)
Output: