skip to Main Content

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


  1. You’re testing whether the whole word is in the array of consonants, not counting each character. You need to loop over the characters.

    $word = $woerter[$random];
    for ($i = 0; $i < strlen($word); $i++) {
        if (in_array($word[$i], $konsonanten)) {
            $zaehler++;
        }
    }
    
    Login or Signup to reply.
  2. 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 of strlen()).

    Code: (Demo)

    foreach ($woerter as $word) {
        echo "Consonants found in $word: " . strlen(str_ireplace(['a', 'e', 'i', 'o', 'u'], '', $word)) . "n";
    }
    

    Output:

    Consonants found in Maus: 2
    Consonants found in Automobil: 4
    Consonants found in Schifffahrt: 9
    Consonants found in Hund: 3
    Consonants found in Katze: 3
    Consonants found in Ziege: 2
    Consonants found in Stanniolpapier: 8
    Consonants found in Elefant: 4
    Consonants found in Isopropylalkohol: 10
    Consonants found in Schwimmbad: 8
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search