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
https://forums.phpfreaks.com/topic/150132-solved-2-arrays-in-foreach-loop/
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";
   }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.