Search code examples
phparraysfor-looptextboxarray-filter

Can't figure out what's wrong with this for loop also array_filter maybe being funny


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.


Solution

  • 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;
        }