Search code examples
phphtmlarraysmultidimensional-arraysuperglobals

Multidimensional associative array in $_POST returns only last value


I've tryed to make a multidimensional associative array but only one value is returned in the $_post.

See working example:

<html>
<?php
    if (isset( $_POST['form_submit'])){
        $Step=$_POST['form_submit'];
        If ($Step>1) $Step=0;
    }else{
        $Step=0;
    }
switch ($Step) {
    case 0:
        echo '
        <form method="post">
        <input name="Txt[First]" type="text"/>
        <input name="Txt[First][Second]" type="text"/>
        <input name="Txt[First][Second][Third]" type="text"/>
        <input name="Txt[First][Second][Third][Fourth]" type="text"/>
        <button type="submit" name="form_submit" value="'.($Step+1).'">submit</button>
        </form>';
    break;

    case 1:
        echo '<br/></br>print_r($_POST):<br/>';
        print_r($_POST);
    break;
}
?>
</html>

edit

if I add "[]" in the end of each input name I'll have all the values but in the wrong way:
$_POST wil be like:

Array ( 
    [Txt] => Array ( 
        [First] => Array ( 
            [0] => one 
            [Second] => Array ( 
                [0] => two 
                [Third] => Array ( 
                    [0] => three 
                    [Fourth] => Array (
                        [0] => four 
                ) 
            ) 
        ) 
    ) 
)

but I need something like:

$_Post[First] => one  
$_Post[First][Second] => two  
$_Post[First][Second][Third] => three  

...and so on


Solution

  • What you want isn't possible. You can only have indexes in an array, but if $_POST['Txt']['First'] is a string like one then it can't also be an array with ['Second'] index.

    You can put the text of each level in a named element:

        <form method="post">
        <input name="Txt[First][text]" type="text"/>
        <input name="Txt[First][Second][text]" type="text"/>
        <input name="Txt[First][Second][Third][text]" type="text"/>
        <input name="Txt[First][Second][Third][Fourth][text]" type="text"/>
        <button type="submit" name="form_submit" value="'.($Step+1).'">submit</button>
        </form>';
    

    Then the result will be:

    $_Post['Txt'][First]['text'] => one  
    $_Post['Txt'][First][Second]['text'] => two  
    $_Post['Txt'][First][Second][Third]['text'] => three  
    $_Post['Txt'][First][Second][Third][Fourth]['text'] => three