Jump to content

Email form to multiple recipients / checkboxes


tcwaage

Recommended Posts

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[] = "[email protected]";
$recipient[] = "[email protected]";

$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!
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):
[code]<?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>';
?>[/code]
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:
[code]<?php
$recipient['recipient 1'] = "[email protected]";
$recipient['recipient 2'] = "[email protected]";

$tmp = array();
if (isset($_POST['email']))
   foreach ($_POST['email'] as $who)
       if (isset($recipient[$who])) $tmp[] = $who;
$mailto = implode(',',$tmp);
?>[/code]
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

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.