array key from a select box?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bal
Forum Newbie
Posts: 9
Joined: Tue May 27, 2008 11:45 am

array key from a select box?

Post 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!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: array key from a select box?

Post by Christopher »

Code: Select all

echo '<select name="colorvalue'.$a.'[]">';
 
echo '<select name="quantity'.$a.'[]">';
(#10850)
Bal
Forum Newbie
Posts: 9
Joined: Tue May 27, 2008 11:45 am

Re: array key from a select box?

Post by Bal »

Isn't that just two separate arrays?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: array key from a select box?

Post by VladSun »

Maybe you are looking for array_combine()
There are 10 types of people in this world, those who understand binary and those who don't
Bal
Forum Newbie
Posts: 9
Joined: Tue May 27, 2008 11:45 am

Re: array key from a select box?

Post by Bal »

OOoohhhh... that's exactly it. Thanks so much!!!
Post Reply