Creationist
Creationist

Reputation: 100

Passing a variable from foreach loop to php

I am lost with a problem I am working on.

I have a HTML form with a few radio buttons and a submit button. From this form, the user will be able to select one of the radio buttons, and then click submit. This will start the PHP script and the script should pull out words from a string that do not match the number that was selected from the radio button.

Whereas I am comfortable with HTML, PHP is giving me a little more trouble.

Here is where I am stuck:

    $myTok = strtok($fileContents, "\"!@#$%^&*(1234567890).,:;'_?\n\t-[]~{}");

while ($myTok != false){

    $myTok = strtok( "\"!@#$%^&*(1234567890).,:;'_?\n\t-[]~{}");

        foreach ($myTok as $key => $value){
            if (strlen($value == 1)){
                                   //not sure how to return the value to the $resultWords variable here

}
}

$resultWords = 

I have a string (ex. "I am having a hard time with the PHP script.") I am using the strtok() function remove any delimiters that are not needed and that would count as an extra character to the $value in my foreach loop but I am wanting ONLY the words.

So with the foreach loop, I am going through every token value to see if the word matches the length that the user chose. These are the words that I want to remove from the string. So, my new string would look like "I am having a the PHP script" if the user chose radio button 4. I want to do this using a foreach() loop. My biggest confusion is how to return the modified string from the loop back out to the variable $resultWords or if I even have the beginning of my foreach loop setup correctly.

Would it be recommended to use the explode() function to make it all an array before the foreach loop? Sorry, I am a bit newbish with this.

Upvotes: 0

Views: 1976

Answers (1)

Abhishek Saha
Abhishek Saha

Reputation: 2564

You can modify your script in the below way.

$resultWords  = array();
foreach ($myTok as $key => $value){

 if (strlen($value == 1)){

        $resultWords[] = $value;                   

    }
}

//Make use of the array now. 
foreach($resultWords as $key => $value) {

    //$value will contain the words

}

Upvotes: 2

Related Questions