downloads | documentation | faq | getting help | mailing lists | reporting bugs | sites | links | my 
search for in the  
view the version of this page
Last updated: Thu, 21 Aug 2003


An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.

Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.


Specifying with array()

An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.

array( [key =>] value
     , ...
// key may be an integer or string
// value may be any value

$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.

A value can be of any PHP type.

$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42

If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.

// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);


As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square-bracket syntax

You can also modify an existing array by explicitly setting values in it.

This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value
If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array

Note: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.


As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.

Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

// Create a simple array.
$array = array(1, 2, 3, 4, 5);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {

// Append an item (note that the new key is 5, instead of 0 as you
// might expect).
$array[] = 6;

// Re-index:
$array = array_values($array);
$array[] = 7;

The above example would produce the following output:
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [0] => 6
    [1] => 7

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achive the reindex effect by using array_values().

$a = array(1 => 'one', 2 => 'two', 3 => 'three');
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');

$b = array_values($a);
// Now b is array(1 => 'one', 2 =>'three')

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:

$foo[bar] = 'enemy';
echo $foo[bar];
// etc

This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.

ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";

Note: The output from the above is:
Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Good: 2

More examples to demonstrate this fact:

// Let's show all errors

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Let's define a constant to demonstrate what's going on.  We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay as it's inside a string.  Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]";      // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple

When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.

As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:

echo $arr[somefunc($bar)];

This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.

$error_descriptions[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";

because E_ERROR equals 1, etc.

As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.

If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names.

If you convert a NULL value to an array, you get an empty array.


The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.

// this
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
                       4        // key will be 0

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')

Example 6-4. Using array()

// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
// strictly numerical keys
$array = array( 7,
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7, 
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
// empty array
$empty = array();         

Example 6-5. Collection

$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Example 6-6. Collection

foreach ($colors as $key => $color) {
    // won't work:
    //$color = strtoupper($color);
    // works:
    $colors[$key] = strtoupper($color);

/* output:
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW

This example creates a one-based array.

Example 6-7. One-based index

$firstquarter  = array(1 => 'January', 'February', 'March');

/* output:
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'

Example 6-8. Filling an array

// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;

Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.

Example 6-9. Sorting an array


Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.

Example 6-10. Recursive and multi-dimensional arrays

$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                  "numbers" => array ( 1,
                  "holes"   => array (      "first",
                                       5 => "second",

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"; 

You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.

$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same

add a note add a note User Contributed Notes
plyrvt at mail dot ru (Yura Pylypenko)
22-Aug-2003 11:57
In documentation it actually states that you can use strings as an array keys, but it was new for me that this can be _any string_ and not only "word" characters are allowed. It is OK to use (for parser, not for your application consistence)
$arr['Any "string" or, even (%), punctuation! Heh?']='This is cool';
jpipes1 at columbus dot rr dot com
17-Jul-2003 12:51
This utility function will write out all form fields,
including form arrays, as hidden textboxes
function WriteHiddenFormValues() {
  global $HTTP_POST_VARS;
  $sTemp = '';
  foreach ($HTTP_POST_VARS as $FormFieldName=>$FormFieldValue) {
    if (gettype($FormFieldValue) == 'array') {
      $iCount = count($HTTP_POST_VARS[$FormFieldName]);
      for ($i=0;$i<$iCount;$i++) {
        $FormFieldValue = $HTTP_POST_VARS[$FormFieldName][$i];
        $sTemp .= "<input type=\"hidden\" name=\"" . $FormFieldName . "[$i]\" value=\"$FormFieldValue\"/>";
    else {
      $sTemp .= "<input type=\"hidden\" name=\"$FormFieldName\" value=\"$FormFieldValue\"/>";
  echo $sTemp;
I use this function whenever I do a "confirmation" type page, where I want to display what the user has input or modified on the posting form and keep the data in the same fields, so all I have to do is submit the confirmed form data again to the "final" page.
akamai at veloxmail dot com dot br
17-Jul-2003 06:22
It is quite simple, but don't forget when you'll using foreach with forms arrays.

If your field name is:
<input type="checkbox" name="foo['bar'][]" ...
It doesn't work.

This should work:
<input type="checkbox" name="foo[bar][]" ...
electronerd at hotmail dot com
15-Jul-2003 03:27
To all of you who keep saying that using the '[]' notation to indicate an array is invalid: You haven't read the specification very carefully. The 'name' attribute of the 'input' element is of type 'CDATA' not 'NAME'. Have a look at the DTD at
agape_logos at shaw dot ca
12-Jul-2003 06:59
I was having trouble getting javascript arrays and php arrays to work together with a Check All checkboxe.  Here is a simple solution.  Clicking the 'Check All' checkbox will check all checkboxes on the form.

<script language="JavaScript">
function chkAll(frm, arr, mark) {
  for (i = 0; i <= frm.elements.length; i++) {
      if(frm.elements[i].name == arr) {
        frm.elements[i].checked = mark;
    } catch(er) {}

<form name='foo'>
<input type="checkbox" name="ca" value="1" onClick="chkAll(this.form, 'formVar[chkValue][]', this.checked)">
for($i 0$i 5$i++){
"<input type='checkbox' name='formVar[chkValue][]' value='$i'>");

Dean M.
luis dot domingues at prodigentia dot com
26-Jun-2003 03:14
Displays every element in a complete multidimensional array:

function ShowEntireArray($array,$root)
  foreach (array_keys($array) as $element)
      ShowEntireArray($my_array,$root . "[" . $element . "]");
      echo($root . "[" . $element . "]=" . $array[$element]);
bammer at bammerboy dot com
17-Apr-2003 11:07
Or, here's an example of a random array display:

= array( 
'1'     => array('apple','orange','bannana'), 
'2' => array('celery','cucumber','onion')); 

print_r ($arr[rand(1,2)][rand(0,3)]); 
chroniton .at. gmx .dot. li
27-Mar-2003 02:13
I didn't find this anywhere in the docs and i think it is worth a mention:

$a[] = &$a;

// will output:

    [0] => Array


// this means that $a[0] is a reference to $a ( that is detected by print_r() ). I guess this is what the manual calls 'recursive arrays'.
paolitooo at yahoo dot com
13-Mar-2003 03:19
For everybody to want send a array from one page a other page la solution is easy. every element of array must be send like hidden.

= array("peru","machu picchu","maca","los incas","greit");
<form name = "form" action="pag2.php"  method = "post">
<?php   for ($lo=0;$lo<sizeof($arraydata);$lo++) { ?>
<input type="hidden" name="opcion[<?=$lo?>]" value="<?=$arraydata[$lo]?>">
<input type="submit" name="enviar">
for ($lo=0;$lo<sizeof($opcion);$lo++) {
"word  $opcion[$lo]<br>";
I hope this helps .
Anllelo Carreazo Yrizales.
07-Mar-2003 07:28
"Using NULL as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets."

If you create an array like this:
$foo = array(null => 'bar');
And then want to access 'bar', you must use this syntax:
echo $foo['']; // notice the two single quotes

This will of course cause a fatal error:
echo $foo[];
16-Jan-2003 09:28
/* It helps to think of numeric indices
 * in the same way as string indices...
 * That is, the order in which they are
 * added in determines the internal order,
 * not the index. For example:

 // for string indices:
$foo["c"] = "c";
$foo["b"] = "b";
$foo["a"] = "a";

/* prints:
    [c] => c
    [b] => b
    [a] => a
 // likewise, for numerical indices:
$bar[2] = 2;
$bar[1] = 1;
$bar[0] = 0;

/* prints:
    [2] => 2
    [1] => 1
    [0] => 0

/* If you are unsure of what the *internal* order
 * of your array is, either use a for() loop, or
 * use the array sorting functions.
11-Dec-2002 04:45

Here is an array difficultly to watch for.
The numeric indices into an array are NOT sequential, they are associative

  // define an array with an offset of one   
$AnArray = array (=> "Dog""Cat""Bat");
// add an element to the 0 index
$AnArray[0] = "Rat";
// print this
// get this output

  Array ( [1] => Dog [2] => Cat [3] => Bat [0] => Rat )

The new value was added at the end, not the beginning as intended.
Try using the push/pop/shift/unshift functions if order is
important in the array. 
// This would have the proper effect from the example.
// array_unshift($AnArray,"Rat");
The index will not unshift to less then 0 so additional unshift calls will
begin to change the indices of the remaining elements.

Or use the ksort() function to sort the keys.
30-Nov-2002 07:10
Dereferencing arrays takes some time, but is not terribly expensive.
I wrote two dummy loops to test performance:
for ($i =0; $i < count($a); $i++) {
 $x = $a[$b[$i]];
 $y = $a[$b[$i]];
 $z = $a[$b[$i]];
for ($i =0; $i < count($a); $i++) {
 $q = $b[$i];
 $x = $a[$q];
 $y = $a[$q];
 $z = $a[$q];

The first loop is 6.5% slower than the second.  Meaning that dereferencing arrays is not terribly expensive, unless you do it a whole lot. I would expect that each extra reference costs about 3% in speed. The lesson is that if you're going to be using a specific value in an array for a number of operations, you can gain a little speed by assigning it to a temp variable (or creating a reference with $q = &$b[$i]) but it's not worth getting crazy over.
I tested this with iterations of 10,000 and 100,000 on php 4.2 and the results were consistent.
t dot kloppenburg at billiton dot de
26-Nov-2002 09:19
When you have to extend an array like those in example 7-4 or 7-10, you always have to double check if there's a comma after every line but the last.

That's annoying.

Some day I discovered that it is possible to write a comma even after the last element, so you can just copy&paste array element lines without the comma-trouble:

$a_fields = array(
    "foo" => "bar",
    "yellow" => "green",
    "fish" => "banana",    /*  with comma! :) */

I really hope, the php parser doesn't think this is an syntax error in some future versions...
19-Oct-2002 12:57
Why array-style names won't work with Javascript is actually quite logical. If you take:

<input type="text" name="Settings[Name]">

as an example, then this JavaScript code:


won't work, of course! Name is an undefined constant in this case, as it's interpreted as a constant, not as a string... But adding quotes won't help you:


Since the name="Settings[Name]" in the tag won't result in a "Settings"-subarray of the form.FormNameHere.elements array in the DOM.

The solution? Use this:


"Settings[Name]" is looked up in the elements array, and is found... The elements array is a hash, so strings can be used as keys!
mu at despammed dot com
15-Oct-2002 01:50
Recursive arrays and multi-dimensional arrays are the same thing and completely identical.

The following confirms this:

$fruits1["european"]["green"] = "Apple";
$fruits2 = array ( "european"  => array ( "green" => "Apple"));
print ($fruits1 === $fruits2);

Result: 1 (= true)
mike at connexions dot co dot uk
29-Aug-2002 12:41
[Editor's note: Use of array_values will also do this, e.g.
$array = array_values($array);]

An easier way to re-index an array after unsetting an element is:


Much easier on the eyes than the above method!
rytier at email dot cz
16-Aug-2002 09:37
re: post
one of those recommended practices...

echo "value = $array[key] \n";

is deprecated - see above "Array do's & don'ts".
The best way is either using curly brackets...

echo "value = {$array['key']} \n";

or "dot splitting" the string and still quoting the key.

echo "value = ".$array['key']." \n";
slava at nospam dot trushkin dot net
30-Jul-2002 11:20
When using array inside double-quoted string key should be single-quoted
only if you use curly braces around variable like this:

$array = array('key' => 'value');

incorrect syntax:

echo "value = $array['key'] \n";
echo "value = {$array[key]} \n";

first line compiler won't even compile
on second line compiler will consider "key" as contant and will show warning if error_reporting is E_ALL

correct syntax:

echo "value = $array[key] \n";
echo "value = {$array['key']} \n";

on first line: no curly braces - no quotes
second line: use curly braces - should use quotes
maxim at php dot net
21-Jun-2002 12:58
"A key is either a nonnegative integer or a string..."

This is incorrect. If you try this code:


[-5] = 'minus five';
$array[]   = 'minus four ';
$array[]   = 'minus three';
$array[]   = 'minus two';
$array[]   = 'minus one';
$array[]   = 'zero';
$array[]   = 'one';
$array[]   = 'two';
$array[]   = 'three';
$array[]   = 'four';



the result would be:

    [-5] => minus five
    [-4] => minus four
    [-3] => minus three
    [-2] => minus two
    [-1] => minus one
    [0] => zero
    [1] => one
    [2] => two
    [3] => three
    [4] => four

I will fix this in the documentation.

Maxim Maletsky,
hramrach_L at centrum. cz ;-)
11-Jun-2002 07:40
Arrays can be merged using + as discussed in the notes for array_merge.
Markus dot Elfring at web dot de
31-May-2002 05:04
It seems to me that the use of brackets with multidimensional arrays is not described here.

But the following examples work:
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';
philip at boone dot at
25-May-2002 08:06
For all of you having problems when using php arrays in an HTML form input field name, and wanting to validate the form using javascript for example, it is much easier to specify an id for the field as well, and use this id for validation.


<input type="text" id="lastname" name="fields[lastname]">

then in the javascript check:

if(formname.lastname.value == "") {
     alert("please enter a lastname!");

This works very well. If you have any problems with it, let me know.
phresno at concept-factory dot com
22-May-2002 05:15
to echo multidimensional arrays put the variable in {}'s

$array[$i][$j] = $i $j;
"Array[$i][$j]: $array[$i][$j]\n";

Array[0][0]: Array[0]
Array[0][1]: Array[1]
Array[0][2]: Array[2]
Array[1][0]: Array[0]
Array[1][1]: Array[1]
Array[1][2]: Array[2]
Array[2][0]: Array[0]
Array[2][1]: Array[1]
Array[2][2]: Array[2]

while the code:
$array[$i][$j] = $i $j;

will properly display the values as such:
Array[0][0]: 0
Array[0][1]: 1
Array[0][2]: 2
Array[1][0]: 1
Array[1][1]: 2
Array[1][2]: 3
Array[2][0]: 2
Array[2][1]: 3
Array[2][2]: 4
ian at vplex dot com
02-Apr-2002 05:16
PHP Arrays and Javascript form checking. 
Problem: how to use javascript to check a form with MyArray[] form elements

Solution: Here is "one" way to solve javascript form checking with MyArray[]type names. Have only checked this with IE5+.  It cleverly highlights the <p id=num> html element. This could work
with input, span, div etc...
This javascript is a modification of some clever code I found off some unamed(?)
website. I was really tired, got a copy and went to bed. If you are the javascripts original author, please claim the original base code.

<script language="JavaScript">

function check() {
  var max = document.forms[0].length-1;
  var retval = true;
  //alert("checking..."+max+" inputs.");

  for (i = 0; i < max; i++) {
    if (document.forms[0][i].value == '') {
      //alert(i+" is empty");
      document.all["l"+i].style.border = "1px #FF0000 solid";
      retval = false;
    } else {
       //alert(i+" is not empty");
       document.all["l"+i].style.border = "1px #00FF00 solid";

  if( retval == false ) {
       alert("Missing Required fields. Missing fields are highlighted in red.");
  } else {
     alert("All fields correctly filled out.");
//     document.iform.submit();         // form is correctly filled out
  return retval;

function warn() {
  if ( == '') {
      = "5px #FF0000 solid";

<form name="iform" action="some.php">
<p id=l0>Name #1
<input type="text" name="fname[]">
<p id=l1>Name #2
<input type="text" name="fname[]">
<p id=l2>Name #3
<input type="text" name="fname[]">
<p id=l3>Email
<input type="text" name="email">

NOT a submit button. check() will
submit the form if passed all checks
<input type="button"

sssolomon at hotmail dot com
16-Mar-2002 01:26
For forms I use "${$foo}" thing:
if ($action=="")
  echo "<form method=\"post\" action=\"form.php\">";
  $amount=3; //(or input on another form)
  For ($loopVar=0; $loopVar<$amount; $loopVar++)
    printf ("Input number %s <input type=\"text\" name=\"%s\">", ($loopVar+1),$loopVar);
  echo "<input type=\"hidden\" name=\"action\" value=\"submit\"><input type=\"hidden\" name=\"amount\" value=\"$amount\"><input type=\"submit\" name=\"submit\" value=\"submit\"></form>";
}elseif ($action=="submit")
  for ($loopVar=0; $loopVar<$amount; $loopVar++)

I like this way best.  You can also have multiple inputs.  Just for the second "printf()" use:
printf ("Input number %s <input type=\"text\" name=\"%s\">", ($loopVar+1),($loopVar+1)*1000000);

and for the loop change ${$loopVar} to ${$((loopVar/1000000)-1)};

That is so that you don't have 2 fields the same "name=" unless the person asks to input more than 1 million numbers...
paul_williams at dstoutput dot com
14-Mar-2002 06:57
My trick for using array input fields with javascript and PHP follows

  <select size=6 name="MyArray" multiple>

This allows you to access the list control in JavaScript by document.formname.MyArray.  When it's time to submit, have an onClick (or onSubmit) handler to do the following:"MyArray[]";

Works great, and satisfies the Principle of Least Astonishment (as much as can be under these conditions IMHO).
andrew at majiclab dot ab dot ca
18-Jan-2002 10:29
In addition to some of the notes already given, I have found the following very useful!  In an HTML form, you can use arrays:

<input type=text name=MyArray[]>

However, a more useful application would be like this:

<input type=text name=MyArray[Settings][Name]>
<input type=text name=MyArray[Settings][Age]>
<input type=text name=MyArray[Prefrences][Color]>

And so on.  PHP will parse it all properly for you.  You can have as many dimensions to the array as you would like, I suppose.  Another good reason that this works well:

foreach( $MyArray[ 'Settings' ] as $Param => $Value )
     @eval( "\$this->$Param = \"$Value\";" );

That will go through all the parameters for settings and assign to the $this object.  This is useful if you are using sessions, and you have an object defined as a session variable, like user.  Then you can just run $User->LoadFormParams() and run the loop above, and your settings are all put into the object!!!

Hope this gives some of you some crazy ideas!!

-Andrew "Percy" Hanna
mrberti at earthlink dot net
11-May-2001 06:41
One may want to take note of the print_r() function. Using it, one can print an array directly to the browser.

= array( 
'fruits'     => array('apple','orange','bannana'),
'vegetables' => array('celery','cucumber','onion'));

print_r ($arr);

Array ( [fruits] => Array ( [0] => apple [1] => orange [2] => bannana ) [vegetables] => Array ( [0] => celery [1] => cucumber [2] => onion ) )
info at knomaze dot com
10-Feb-2001 06:37
PHP, HTML & Javascript

To say I was bashing my head against the wall for 6 days on this is an understatement - niaht ( helped me find a partial answer to this nagging problem:

FAQ Section 8.1 states that we can set the name element in an input object to an array as indicated:

    <input name="MyArray[]">
    <input name="MyArray[]">
    <input name="MyArray[]">
This produces a array that gets sent to the PHP script when the form returns. Further, that you must not use indices with arrays in HTML!

Well based upon my recent experience with PHP4 - leaving the indices out may not necessarily be the best thing, especially when dealing with two dimensional arrays. Further, IE and Netscape do not handle the resulting element name in the same way. Although we found a method that worked in IE, it didn't work for Netscape and as I am a fan of finding single solutions that work for both browsers, here is a way that you can reference these variables in Javascript.


This will work regardless of which browser you are using. The drawback is that it may take some manual effort to find the right index value for "i" the first time around. The javascript book I have here suggests that in the application I've been working on, the elements I am interested in started at element[6] - in fact they started at element[7] for both IE and NS, so it would be wise to cross check the indices before trying this at home.
mjp at pilcrow dot madison dot wi dot us
22-Feb-2000 06:18
Those with a perl background may be surprised to learn that the 'thick arrow' and comma operators are not synonymous in array construction.

For example, the following are equivalent:

$ary = array("foo" => "bar", 1, 2);
$ary = array("foo" => "bar", 0 => 1, 1 => 2);

 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat 01 Nov 2003 04:13:36 EST EST