Jump to content

PHP loop statements for form variables


kienthucnet

Recommended Posts

Hi,

 

I have a form the uses PHP mail to email inputted form data to an email address. The form has has 4 select fields which contain the same 10 colours in each. For example, when a user selects Light Green from the first select field, the value of #66FF66 is assigned to a variable e.g. (color-select-1-hex, color-select-2-hex, color-select-3-hex and color-select-4-hex).

 

What I need is advice on how I go about creating a loop statement which runs through each of the 4 select field user inputs, creates a new variable (e.g. color-select-1-name) and assigns 'Light Green' to it. I need to keep color-select-1-hex equal to #66FF66.

 

What is the recommended approach here? Thanks for any help!

Link to comment
Share on other sites

 

What is the recommended approach here?

To not use separate variables. You should be using arrays

 

You would start by naming your <select> fields as color[]

<select name="color[]">
   ... color options ...
</select>

This will mean when you submit the form $_POST['color'] will be an array containing all four selected values from the select fields

 

To loop over the values you simple use a foreach loop

echo "Your chosen colors are: ";
foreach($_POST['color'] as $color)
{
   echo "$color<br />";
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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