Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count letters of random string of an array

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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++;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading