lundi 24 août 2015

Find right index of checkbox

I am trying to combine form results. So if a checkbox is checked I want to save the ID of the checkbox combined with the value of the select box in the same row. I do this by looping through the checkbox $_POST array and use the index to find the right result of the selectbox $_POST array.

The problem is is that if I for example check the second checkbox and the first not, the index of the checkbox array is '0' (1 item) and the index of the selectbox array is '1' (2 items). With the result that I get the first selectbox, which is the wrong one:

$_POST['selectbox'][0]

How can I get the right index?

HTML:

<form method="post">
    <ul>
        <li>
            <input type="checkbox" name="checkbox[]" value="10">
            <select name="selectbox[]">
                <option value="value_1">Value 1</option>
                <option value="value_2">Value 2</option>
            </select>
        </li>
        <li>
            <input type="checkbox" name="checkbox[]" value="11">
            <select name="selectbox[]">
                <option value="value_1">Value 1</option>
                <option value="value_2">Value 2</option>
            </select>
        </li>
    </ul>
</form>

PHP:

<?php
if( ! empty( $_POST['checkbox'] ) ) {
    $examples = array();
    foreach( $_POST['checkbox'] as $index => $value ) {
        $examples[] = array(
            'checkbox'  => $value,
            'selectbox' => $_POST['selectbox'][$index]
        );
    }
}
?>




Aucun commentaire:

Enregistrer un commentaire