PHP foreach loop inside foreach loop

I am trying to make a foreach loop inside a foreach loop.

I have a form in which the user enters some text and sends the package. On the server site, I scan the array with email addresses and send a text message.

Now I also want the user to be able to use variables in the text box, for example $ name. So my loop should first go through emails, and then str_replace the userinput $ name variable with the names in my array.

The loop works fine with the email part ($ tlf), but does not replace the $ name part.

Can someone say what I'm doing wrong?

$message = stripslashes(strip_tags($_POST['message2'])); $tlf=array("name1","name2"); $test=array("mname1", "mname2"); $subject = "Hello world"; $from = " me@gmail.com "; $headers = "From: $from"; foreach($tlf as $name){ $to = $name. "@gmail.com"; foreach($test as $navn){ $message = str_replace('$navn', $navn, $message);} mail($to,$subject,$message,$headers); } 

Thank you very much.

EDIT: An email was sent at the exit. Say the user type in "hello $ name". I want him to iterate over the $ tlf array first, in this case, create 2 letters. It starts with $ to in the first loop. It works.

Now the next loop should recognize the user input "hello $ name" and execute the loop through the $ test array, replacing the user variable $ name.

The output will be sent 2 emails.

  • Mail output: to the address: name1@gmail.com message: hello mname1

  • Email output: to: name1@gmail.com message: hello mname2

Let me know if I need to explain better, it's hard for me to explain, sorry.

+4
source share
2 answers

Is this what you want?

 $message = stripslashes(strip_tags($_POST['message2'])); $tlf=array( array("email" => "name1", "name" => "mname1"), array("email" => "name2", "name" => "mname2") ); $subject = "Hello world"; $from = " me@gmail.com "; $headers = "From: $from"; foreach($tlf as $contact){ $to = $contact["email"] "@gmail.com"; $replacedMessage = str_replace('$navn', $contact["name"], $message); mail($to,$subject,$replacedMessage,$headers); } 
+1
source

When you do the following:

 str_replace('$navn', $navn, $message) 

Then all literal occurrences of $navn will be replaced (first, second, third, ...). Thus, starting this cycle a second time cannot replace anything else.

You will need to define two placeholders or make some difference or use preg_replace_callback if you want to declare in which order (or other logic) the possible replacement strings are applied.

If you told us (but you didn’t), you would like to replace the first appearance at each iteration, then the usual preg_replace(.., .., .., 1) will work.

+2
source

All Articles