0

I have a form that includes multiple checkbox sets, where the name of the input is dynamically created (name="'. $name .'[]"). The HTML result looks something like this:

<tr>
<td><input type="checkbox" name="1[]" value="Jan"/></td>
<td><input type="checkbox" name="1[]" value="Feb"/></td>
</tr>
<tr>
<td><input type="checkbox" name="2[]" value="Jul"/></td>
<td><input type="checkbox" name="2[]" value="Sep"/></td>
<td><input type="checkbox" name="2[]" value="Dec"/></td>
</tr>
<tr>
<td><input type="checkbox" name="3[]" value="May"/></td>
<td><input type="checkbox" name="3[]" value="Aug"/></td>
</tr>

When its submitted, I know it comes across as a multi-dimensional array but how can I get the value of the input's name using a foreach statement? Currently I have tried this but it does not give me the value of the input's name.

foreach ($_POST as $task){
    foreach ($task as $key => $month){
        echo '<p>Task ID is: '. $task .' and the month check is '. $month .'';
    }       
}

Which returns (if all is checked):

Task ID is: Array and the month check is Jan
Task ID is: Array and the month check is Feb
Task ID is: Array and the month check is Jul
Task ID is: Array and the month check is Sep
Task ID is: Array and the month check is Dec
Task ID is: Array and the month check is May
Task ID is: Array and the month check is Aug

I need the input name as the Task ID:

Task ID is: 1 and the month check is Jan
Task ID is: 1 and the month check is Feb
Task ID is: 2 and the month check is Jul
Task ID is: 2 and the month check is Sep
Task ID is: 2 and the month check is Dec
Task ID is: 3 and the month check is May
Task ID is: 3 and the month check is Aug

Thank you in advanced for any help with this.

0

1 Answer 1

2

Your $_POST will have the form post names as keys. So, you will to have to get the key from your first foreach loop like below:

foreach ($_POST as $task_name => $task){
    foreach ($task as $key => $month){
        echo '<p>Task ID is: '. $task_name .' and the month check is '. $month .'';
    }       
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I thought I had tried that way too but I must have missed something.

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.