0

I have a table of checkboxes and textboxes that is generated from a database. When i check 2 out of 3 checkboxes and write in 2 out of 3 textboxes. Checkbox array has 2 elements and textbox array has 3. I tried to use array_filter but it doesn't work or something...

$textbox_array=array_filter($_POST['text']);
$checkbox_array = $_POST['check'];
    for ($i = 0; $i < count($checkbox_array); $i++) {
        $textbox = $textbox_array[$i];
        $checkbox = $checkbox_array[$i];

        echo $textbox; 
        echo '-'; 
        echo $checkbox;
    } 

i check checkboxes 9 and 10, and put values 1 and 2.

this is what i get: 1-9-10 i should get:1-2-9-10

Help me please.

Jorge Campos
  • 22,647
  • 7
  • 56
  • 87
Foogley
  • 3
  • 3
  • 1
    Unchecked checkboxes are NOT sent in post data, this is the expected behavior. If for some reason you need them sent, see here: http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked – Steve Jul 16 '14 at 14:52
  • I don't need them sent also I don't need the empty textboxes to be sent. – Foogley Jul 16 '14 at 14:56

2 Answers2

1

The problem is that $textbox_array does not have the same array keys as $checkbox_array.

One fix is to reset the array keys of $textbox_array.

Instead of

$textbox_array=array_filter($_POST['text']);

Try

$textbox_array=array_values(array_filter($_POST['text']));
James
  • 20,957
  • 5
  • 26
  • 41
1

Your problem is that with array_filter() -> Array keys are preserved.

You need to call array_values() to reset the array keys -> array_values() returns all the values from the array and indexes the array numerically

$textbox_array=array_filter($_POST['text']);          
$textbox_array=array_values($textbox_array);
$checkbox_array = $_POST['check'];
    for ($i = 0; $i < count($checkbox_array); $i++) {
        $textbox = $textbox_array[$i];
        $checkbox = $checkbox_array[$i];

        echo $textbox; 
        echo '-'; 
        echo $checkbox;
    } 
Sean
  • 12,443
  • 3
  • 29
  • 47