Submitting Multi-Dimensional Array Data to PHP

Distributed Systems with Node.js, O'Reilly 2020, has been published!

This article is regarding an under-documented PHP feature when dealing with form data received from an HTML page (this works with both GET and POST data). If you name your HTML elements the proper way, you are able to send multidimensional arrays (or single dimension arrays for that matter) to your PHP script and access them using the $_POST superglobal array. You can use both associative arrays and numerical arrays. Pretty much any type of array that you can build in native PHP can be represented in an HTML form.

Here's the syntax you've been waiting for. The first example will use numerical indexes, which will be automatically calculated by PHP, similar to doing $arr[] = 'a'; $arr[] = 'b';:

<input name="address[]" value="1313 Mockingbird Ln" />
<input name="address[]" value="Appartment D" />
<input name="airport[4]" value="DET" />
<input name="airport[7]" value="JFK" />
<input name="person[john]" value="man" />
<input name="person[sue]" value="woman" />
<input name="person[john][name]" value="Johnathan" />
<input name="person[john][age]" value="39" />

Now, if we POST this data to the server, and do a <?php print_r($_POST); ?>, we will get the following data structure:

Array
(
    [address] => Array
        (
            [0] => 1313 Mockingbird Ln
            [1] => Appartment D
        )

    [airport] => Array
        (
            [4] => DET
            [7] => JFK
        )

    [person] => Array
        (
            [john] => Array
                (
                    [name] => Johnathan
                    [age] => 39
                )

            [sue] => woman
        )
)

And that's all there is to it! My examples don't really show off the usefulness of this feature though. The best usage is for iterating over a large list of data returned to the server, especially when dealing with dynamically generated lists of data inputs. For example, if you have an application where you need to edit X number of employees, and you make changes to only some of them (but not all of them), this will give you a list of specific items.

Tags: #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, is an O'Reilly published author, and is an organizer of NodeSchool SF.