Jump to content

[SOLVED] 2 arrays in foreach loop


AdRock

Recommended Posts

When i connect to the database I create 2 arrays

while ($row = $result->fetch()) {
$emails[] = $row['email'];
$names[] = ucwords($row['first_name']);
}

 

and i want to use both arrays in my foreach loop

 

at the moment if does the foreach using the email array but it doesn't do the foreach for the names array so it applies the same name to each of the emails instead of goping through each email address and getting each name

 

foreach($emails as $email) {
$to = $email;
	  
$HTML = str_replace($nameholder, $names, $HTML);
$HTML = str_replace($emailholder, $email, $HTML);
	  
$result = sendHTMLemail($HTML,$from,$to,$subject);
	  
if($result != 'Correct') {
	return "Emails not sent";
}
}

 

How can i get each name in the array to match each email?

Link to comment
Share on other sites

you can do it like this:

foreach($emails as $n=>$email) {
   $name = $names[$n];
   $to = $email;
       
   $HTML = str_replace($nameholder, $names, $HTML);
   $HTML = str_replace($emailholder, $email, $HTML);
       
   $result = sendHTMLemail($HTML,$from,$to,$subject);
       
   if($result != 'Correct') {
      return "Emails not sent";
   }
}

 

but is there a reason you don't just use a multidimensional array?

 

$data = array();
while ($row = $result->fetch()) {
   $data[] = array(
      'email' => $row['email'],
      'name' => ucwords($row['first_name'])
   );
}

foreach($data as $item) {
   $to = $item['email'];
       
   $HTML = str_replace($nameholder, $item['name'], $HTML);
   $HTML = str_replace($emailholder, $item['email'], $HTML);
       
   $result = sendHTMLemail($HTML,$from,$to,$subject);
       
   if($result != 'Correct') {
      return "Emails not sent";
   }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.