Jump to content


Photo

Email form to multiple recipients / checkboxes


  • Please log in to reply
2 replies to this topic

#1 tcwaage

tcwaage
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 04 April 2006 - 08:51 AM

I'm trying to make a email form where the sender can select his/her recipients by checking them.

Here is my form code that diplays the recipients and checkboxes:

<input type="checkbox" name="email[]" value="recipient 1" /> Recipient 1
<input type="checkbox" name="email[]" value="recipient 2" /> Recipient 2

And this is the php code:

$recipient[] = "mail1@somewhere.com";
$recipient[] = "mail2@somewhere.com";

$mailto="";
foreach(array_intersect(array_keys($recipient),array_values($_POST['email']))
as $val)
{
$mailto.=$recipient[$val].',';
}
$mailto=trim($mailto,',');

I keep getting these error messages:

Warning: array_values(): The argument should be an array

Warning: array_intersect(): Argument #2 is not an array

Warning: Invalid argument supplied for foreach()

And in addition the script displays a "not a valid email" error message, but this is caused by the array error.

Please help!

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 04 April 2006 - 01:39 PM

If you put these debuging lines before and after the array_intersect, you will see that the intersection of your two arrays is NULL (and not an array):
<?php
echo '<pre>' . print_r($_POST['email'],true) . '</pre>';
echo '<pre>' . print_r($recipient,true) . '</pre>';
$tmp = array_intersect(array_keys($recipient),array_values($_POST['email']));
echo '<pre>' . print_r($tmp,true) . '</pre>';
?>
This is because the keys of the $recipient array are numerical while the values of the $_POST['email'] array are strings.

A better way to do this would be:
<?php
$recipient['recipient 1'] = "mail1@somewhere.com";
$recipient['recipient 2'] = "mail2@somewhere.com";

$tmp = array();
if (isset($_POST['email']))
   foreach ($_POST['email'] as $who)
       if (isset($recipient[$who])) $tmp[] = $who;
$mailto = implode(',',$tmp);
?>
While keeping your form definition intact.

The array $tmp and using the implode() function alliviates the need to trim the final comma from the generated list.

Ken


#3 tcwaage

tcwaage
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 05 April 2006 - 08:27 AM

i still get an error msg. saying " Invalid argument supplied for foreach()"




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users