Jump to content

[SOLVED] foreach question


ballhogjoni

Recommended Posts

Hey all, this is kinda complicated so plz bare with me. I have a form where you can send an email to multiple friends. This form only has two fields, one for the names and one for the emails. You seperate the names and emails by commas. If someone enters more than one name and more than one email I would like to email each email. The problem is being able to extract the names and emails and put them in a loop that sends out mail. I want to put the name into the body of the email. Look at my code and it should help explain what I am trying to do. My output just echoes the first email and first name. It doesn't echo all the names and all the emails.

 

<?php
$receiverEmails = explode(',',$_POST['email_to']);
$receiverNames = explode(',',$_POST['name_to']);

foreach($receiverEmails as $k=>$v){
$plugEmail = $v;
}
foreach($receiverNames as $k=>$v){
$plugName = $v;
}
for($i=0;$i<sizeof($receiverNames);$i++){
echo $plugEmail.' '.$plugName;
mail($plugEmail,$subject,$body,$headers);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/109025-solved-foreach-question/
Share on other sites

Well, in your loops you just overwite the same variable -- it doesn't achieve anything. Try this:

 

$emails = explode(',',$_POST['email_to']);
$names = explode(',',$_POST['name_to']);
if(count($emails) == count($names)){
    $array = array_combine($emails,$names);
    foreach($array as $email=>$name){
        echo 'Name:'.$name.' Email:'.$email.'<br />';
    }
}else{
    echo 'Names and emails do not match!';
}

That looks good in theory, but for some reason Its throwing an error that I can't see. My screen just shows a blank screen. So I echoed something b4 the array_combine() and it echoed it. So it tells me something isn't working with the array_combine(). any thougts?

after some research array_combine() is only good for php 5+. Here's a tradeoff for php 4+:

 

<?php
if(!function_exists('array_combine')){
function array_combine($keys, $values){
if(count($keys) < 1 || count($keys) != count($values) || !is_array($keys) || !is_array($values)){
return false;
}
$keys = array_values($keys);
$values = array_values($values);
for($x=0; $x < count($keys); $x++){
$return_array[$keys[$x]] = $values[$x];
}
return $return_array;
}
}
?>

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.