How to loop through an array of inputs in a form?

后端 未结 3 429
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 09:47

I am trying to look through some input fields in a form and add them to a database. The user sets the number of fields, so I can\'t do something like the code below because

3条回答
  •  无人及你
    2020-12-11 10:28

    Given:

    
    
    etc...
    

    in your form, you'd loop over them with

    foreach($_POST['foo'] as $index => $value) {
        ...
    }
    

    The [] in the field name will be stripped off by PHP and used as a hint that it should expect multiple values with the same name, causing it to create a sub-array inside $_GET/$_POST to accomodate those extra values.

    You can also suggest which array keys PHP should use, e.g.

    
    
    
    echo $_POST['foo'][1]; // outputs "hi there"
    echo $_POST['foo']['abc'] // outputs "TGIF!"
    

    Multi-dimensional arrays are also supported, using the same notation/access methods.

提交回复
热议问题