0

I have an array that looks something like this:

$array = array(
   'val1' => array('en'=>'Option Title 1','a'=>1),
   'val2' => array('en'=>'Option Title 2','b'=>2),
   'val3' => array('en'=>'Option Title 3','c'=>3)
);

I tried running this code to generate a select box :

function setOptions($array){
    echo '<select name="select">';
    foreach($array as $key_parent => $val_parent){
        foreach($val_parent as $key => $val){
            if($key !== 'en'){
                $option_value = $val;
            }elseif($key == 'en'){
                $option_title = $val;
            }
        }
        echo '<option value"'.$option_value.'">'.$option_title.'</option>';
    }
    echo '<select>';
}

This prints what I expected.

<select name="select">
  <option value="1">Option Title 1</option>
  <option value="2">Option Title 2</option>
  <option value="3">Option Title 3</option>
</select>

However when I print the return value of $_POST['select'] from a form submission, I get Option Title 1, Option Title 2, or Option Title 3, not 1,2 or 3 which I thought was pretty odd.

So this leaves the question, how do I get the values inside of val1, val2, val3 when the key of one of the values in question is unknown(either a,b or c)?

2
  • How is your form being posted? Via AJAX? If so, show us the javascript that handles this. Commented Dec 12, 2012 at 12:43
  • Have you tried <select name="select[]"> and accessing the result accordingly? Commented Dec 12, 2012 at 12:43

1 Answer 1

4

You miss equal in value attribute.

function setOptions($array){
    echo '<select name="select">';
    foreach($array as $key_parent => $val_parent){
        foreach($val_parent as $key => $val){
            if($key !== 'en'){
                $option_value = $val;
            }elseif($key == 'en'){
                $option_title = $val;
            }
        }
        echo '<option value="'.$option_value.'">'.$option_title.'</option>';
    }
    echo '<select>';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.