Adam
Adam

Reputation: 3518

PHP HTML data format

How to process this type of input form:

<form action="update" method="post">
    <table>
        <tr>
            <th>First name</th>
            <th>Last name</th>
        </tr>
        <tr>
            <td><input type="text" name="people[][firstname]" value="John" /></td>
            <td><input type="text" name="people[][surname]" value="Smith" /></td>
        </tr>
        <tr>
            <td><input type="text" name="people[][firstname]" value="Adam" /></td>
            <td><input type="text" name="people[][surname]" value="Boralsky" /></td>
        </tr>
    </table>
</form>

I would expect to receive a multidimensional array, but instead I am receiving this:

array (size=4)
  0 => 
    array (size=1)
      'firstname' => string 'John' (length=4)
  1 => 
    array (size=1)
      'surname' => string 'Smith' (length=5)
  2 => 
    array (size=1)
      'firstname' => string 'Adam' (length=4)
  3 => 
    array (size=1)
      'surname' => string 'Boralsky' (length=8)

Has anybody seen this sort of format?

Upvotes: 1

Views: 51

Answers (1)

jbafford
jbafford

Reputation: 5668

That's happening because that's actually what you're asking PHP to do. [] is the "next array index" operator, so when PHP processes the input, it sees people[][firstname] = John, understands that as "Add to $people[] = ['firstname' => 'John']", and you get:

$people = [
    ['firstname' => 'John'],
];

Then, when we get people[][surname] = Smith, "add to $people[] = ['surname' => 'Smith']". Which then gives us:

$people = [
    ['firstname' => 'John'],
    ['Surname' => 'Smith'],
];

and so on.

What you'll need to do is explicitly set an array key in your html. If this is the only person in the form, then instead of people[], use people[0]. If there are multiple people, then you're going to have to dynamically generate an index for each field common to a person.

Upvotes: 2

Related Questions