Form input field names containing square brackets like field[index]

前端 未结 3 1399
青春惊慌失措
青春惊慌失措 2020-11-28 13:17

I\'ve seen a lot of PHP code that handles form input in which the input field names contain square brackets. I understand that this somehow results in PHP arrays when a PHP

相关标签:
3条回答
  • 2020-11-28 13:55

    To my knowledge, this is a mechanism of PHP internally seeing (and parsing) elements passed via form (GET/POST) with the [] postfix and interpreting them as an array of elements. The HTTP protocol doesn't care, it merely passes the element's name with it's associated value in the query string.

    It's been a normal programming tool as far back as I can remember (I think I even remember it more commonly used for multi-file uploads back when you had "add file" links that appended another element to the form, using the same name (with []) as the previous.)

    The same rules that apply in PHP apply in the form. You can use [] to auto-index the elements (for generic lists) or explicitly list them using element IDs (e.g. file[1], file[2], etc. (following my previous example))

    Yes, multi-dimensional arrays can be used.

    For more information, check out PHP's very own _POST documentation (especially the comments)

    0 讨论(0)
  • 2020-11-28 14:07
    • This is completely php language feature. HTTP knows nothing about arrays. In http either foo or bar[baz] is just a names of variable

    • It is a normal practice

    • Use them when it is handy for you. For example: to group several fields, that belong to one entity, such as news[title] + news[body]

    • Yes. TIAS

    0 讨论(0)
  • 2020-11-28 14:09

    What is the mechanism behind? At which point this names that merely contain brackets are converted to arrays? Is this a feature of the HTPP protocol? Of web servers? Of the PHP language?>

    This is a feature of the PHP language. In fact, the HTTP protocol does not forbid the use of multiple identical GET/POST parameters. According to the HTTP spec, the following:

    foo=bar&foo=baz
    

    Should not result in foo == baz. These are two parameters with two different values. However, PHP will overwrite the former foo with the latest, resulting in $_POST['foo'] == 'baz', even if they could be parsed separately.

    Continuing the previous question, is this a commonly used hack or a normal programming tool?

    It depends on the point of view. In the PHP world, it is completely normal, as the language does not support the specification of multiple parameters of the same name without using the brackets []. In the HTTP world though, foo != foo[].

    What are (all) the rules of using brackets in input field names?

    The same as PHP arrays, except that you don't have to quote string keys.

    Can multidimensional arrays be created this way?

    Yes, you can.

    0 讨论(0)
提交回复
热议问题