0

So basically, I have an array of Modules and I want to have a drop-down menue that users can then select what grade they got. This works fine, however, I would like the results to be stored inside of an array, to however many values they selected. So for example:

If someone selected "40" in Mod1 and in Mod2 they selected "20" then the array would be like this:

mod1=>40

mod2=>20

...

Here is the code so far, it's probably something stupid, I just cannot get my head around it.

<?php

$modules = array('Mod1', 'Mod2', 'Mod3');   

if(!isset($_POST['submitted']))
{
    echo '<form method="post">';

    echo 'Please enter the grades you got for each Module: <br />';
    foreach($modules as $module)
    {
        echo $module . ': <input type="text" name="grades[]" value=""> <br />';
    }
    echo '<br /><input type="submit" name="submit" value="Go!">';
    echo '<input type="hidden" name="submitted" value="TRUE">';

}else{

    $input = $_POST['score[]'];
    foreach($modules as $i => $module){
        $input[$module] = $input[$i];
        var_dump($input[$module] = $i);
        //unset($input[$i]);
    }
    //var_dump($input);

}

?>
1

3 Answers 3

2
<select name="score[<?php echo $module; ?>]">

should get you going :)
the array will look exactly like you narrowed it down in the intro.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use a name that groups the values of the selects in POST into one array:

echo '<select name="score[]">';

You can then use:

$input = $_POST['score[]'];
foreach($modules as $i=>$module){
    $input[$module] = $input[$i];
    unset($input[$i]);
}
var_dump($input);

8 Comments

Thank you. But this shows as "array(3) { [0]=> string(2) "90" [1]=> string(2) "12" [2]=> string(2) "23" }" whereas I want it to be... [Mod1]=> string(2) "90" etc.. How would I do that? Do I need to map the array?
Thanks, but this puts the array now as: "array(3) { ["Mod1"]=> NULL ["Mod2"]=> NULL ["Mod3"]=> NULL }" I don't know why it's giving NULL
@Phorce What happens when you try it without the unset?
@Phorce Strange. Try this and tell me what the output is: $input[$module] = $i;
I get "int(0) int(1) int(2)" I have updated my code in my original post
|
1

just change your name attribute to an array:

echo '<select name="score[]">';

the the $_POST variable will be in an array

2 Comments

Thanks :) It worked! I knew it was something silly. Could you tell me also, why it only shows "Mod1", "Mod3" from my array.. "Mod2" seems to have just disappeared.
it appears that you don't have a closing </select>

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.