Page 1 of 1

array key from a select box?

Posted: Tue May 27, 2008 12:37 pm
by Bal
I'm trying to find a way to store information from a select box in an array. I need the first select box to be the key of the array, and the second to be the value.

This is the code I'm using to generate the boxes:

Code: Select all

<?php
//This will genreate five pairs
for ($a=1;$a <= 5;$a++) {
//This should be the key
echo '<select name="colorvalue'.$a.'">';
echo '<option value="">Choose a color</option>';
echo '<option value="Red">Red</option>';
echo '<option value="Orange">Orange</option>';
echo '<option value="Yellow">Yellow</option>';
echo '<option value="Green">Green</option>';
echo '<option value="Blue">Blue</option>';
echo '</select>';
//This should be the value 1 - 5
echo '<select name="quantity'.$a.'">';
echo '<option value="">Pick a number</option>';
echo '<br />';  
    for ($i=1;$i <= 5;$i++){
        echo '<option value="'.$i.'">'.$i.'</option>';
    }
echo '</select>';   
echo '<br/>';
}
?>
So, I'm using the loop counter to create unique names for the drop boxes. The code used to stuff that into an array is something I am struggling with currently. It doesn't work, but it looks like this..

Code: Select all

 
//validates and outputs array
    for ($b=0;$b <= 5;$b++) {
    $chooser = array ($_POST[colorvalue.$b] => $_POST[quantity.$b]);
    }
    if (!empty($_POST['colorvalue'.$b])){
    foreach ($chooser as $key => $value) {
        print"<p>Your color ".$key." has a value of ".$value."</p>";
}}
 
Ultimately, this array would be broken down again and stored in a table with the key as a foreign key along with the value.

If there is a better way of doing this, boy.. would I like to know about it.

Thanks for any help!

Re: array key from a select box?

Posted: Tue May 27, 2008 3:41 pm
by Christopher

Code: Select all

echo '<select name="colorvalue'.$a.'[]">';
 
echo '<select name="quantity'.$a.'[]">';

Re: array key from a select box?

Posted: Tue May 27, 2008 5:39 pm
by Bal
Isn't that just two separate arrays?

Re: array key from a select box?

Posted: Tue May 27, 2008 5:41 pm
by VladSun
Maybe you are looking for array_combine()

Re: array key from a select box?

Posted: Tue May 27, 2008 6:44 pm
by Bal
OOoohhhh... that's exactly it. Thanks so much!!!