I am having some trouble setting a value to a variable based on the value of the array. Basically I want to assign a subject based on the selection of the recipient using an array. I’ll post my code and that way you can have a full picture.
Here is the code broken down that I’m trying to figure out:
//This is who will get the email based on selection from the $to in the form.
$receivers = array(
1 => 'email1@example.com',
2 => 'email2@example.com'
);
//Set $receivers based on selection of $to from the form.
if(array_key_exists($formData['to'], $receivers))
{
$to = $receivers[$formData['to']];
}
else
{
$to = 'example@example.com';
}
Now here is where I’m having my trouble. I want to have the $subject variable set based on the value of the $receivers array. I also want to keep the option of using a value from a text box on a form, so that I can use this script anywhere with little to no modification.
From what I can tell, this is kinda working. When the form sends out the email it assigns Subject 1 as the subject regardless of the $receivers array value.
If you can help that would be greatly appreciated.
I don’t quite understand what you’re trying do with the code in the second example. Firstly you are missing the condition on the elseif.
Aside from that, perhaps you can alter your $receivers array so that you have a multi-dimensional array (i.e. each element itself is also an array) allowing you to story email addresses as well as subjects?
What I’m trying to do is create a multi-use contact form script that I can use for my site and other projects. The idea for the email address selection setting the subject is to give me the option to exclude a subject input field on the form. I still want the option to have the field if I need it. That is what I’m trying to do with my second block of code. In hopes that it helps here is the complete working script. I just don’t know how to set the array like your suggesting. Is there a way to include the option for the input field?
Having the subject use a input field and using an if statement when there is not a subject input field on the form is really not important at this time. Hence why I was trying to make
Any help would be greatly appreciated…I think it has something to do with my validation that keeps the $to from being set by the switch. It will send to the default every time. Just don’t know where I’m making my mistake. If you can help, please let me know. Thanks!
How do I do that? I’ve tried it and I either get a 500 error or a blank page…can you show me an example of setting the email and subject based on the array?
N9ne’s suggestion was good. I did a slight variation in that I used the email as the array key with the value as subject. Added a sloppy form at end for testing which isn’t needed, but wanted to show that the same $receivers array builds form selection fields.