saurav
saurav

Reputation: 11

Foreach loop for two arrays?

I have two arrays. One for input boxes and other for checkbox.

inputbox[] checkbox[]

inputbox[] checkbox[] . . . . submit button

When I fill check box1 and fill the value in input box1 and try to submit. Foreach fails because it pass all the indexes of input boxes but only passes checked checkbox.

foreach(array_combine($checkbox, $inputbox) as $check => $input) 

Please tell me what can i do?

Upvotes: 0

Views: 209

Answers (2)

swapnilsarwe
swapnilsarwe

Reputation: 1300

if you have a control over the HTML form you can make the form in following manner

<input type="text" name="name[1]" />
<input type="checkbox" name="check[1]" />
<input type="text" name="name[2]" /> 
<input type="checkbox" name="check[2]" /> 
<input type="text" name="name[3]" />
<input type="checkbox" name="check[3]" />
<input type="text" name="name[4]" />
<input type="checkbox" name="check[4]" />

in that case you will get the post array in the following manner

Array
(
    [name] => Array
        (
            [1] => Swapnil
            [2] => 
            [3] => Sarwe
            [4] => Swapnil Sarwe
        )

    [check] => Array
        (
            [1] => on
            [3] => on
        )

)

Now you can loop over the name(input box) and then check isset for the isset($_POST['check'][$key]) and set the default value

Upvotes: 1

Amadan
Amadan

Reputation: 198324

Iterate over textboxes (which are guaranteed to all be present), then fetch the corresponding checkbox (probably by ID, if you have some kind of ID correspondence between them - which you should).

Upvotes: 1

Related Questions