Home > Enterprise >  count letters of random string of an array
count letters of random string of an array

Time:11-22

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:

<?php

    $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.";
    
    
?>

CodePudding user response:

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  ;
    }
}
  •  Tags:  
  • php
  • Related