Last Updated: 09 May 2008


Author: dordal

Using PHP Input Arrays with Javascript

PHP allows you to name multiple form elements with the same name (appended by square brackets):

<form name='myForm'>
<input type='text' name='myInput[0]' id='myInput[0]' />
<input type='text' name='myInput[1]' id='myInput[1]' />
<input type='text' name='myInput[2]' id='myInput[2]' />

When you submit this, the $_REQUEST['myInput'] variable becomes an array with all the values from your input boxes. But how do you access these input boxes in Javascript? You can't do:


because the square brackets are illegal in an identifier in Javascript, even though they are legal in HTML. (In fact, that would try to access the 0th element of the myInput array, which doesn't exist.) Instead, you can use the array notation for accessing a property of an object:


Since myInput[] is now being passed in as a string, and not a JS identifier, you're fine.

Discussion, Sep 29, 2008 08:41 PM

saves me from hell! great information here!!!!, Nov 21, 2008 05:46 PM

Thanks! It was hard to find the answer to this in Google :P, May 13, 2009 09:47 AM


Richard Muir-Gladman, Oct 2, 2010 07:50 PM

If you are accessing more than one control in a function, you can get a significant performance boost by using the following code. The more form elements you need to access, the better the boost.

var elem = document.forms['myForm'].elements; …elem['myInput[0]']…

Richard Muir-Gladman, Oct 2, 2010 07:52 PM

Well, the code tag is buggy…

That should read

var elem = document.forms['myForm'].elements;
… elem['myInput[0]' …

Enter your comment. Wiki syntax is allowed: