Creating an empty 2D array in PHP? Creating an empty 2D array in PHP? arrays arrays

Creating an empty 2D array in PHP?


At its absolute simplest, a 2D dimensional array can be created as:

<?php    $emptyArray = array(array());?>

Or as of PHP 5.4 you can also use:

<?php    $emptyArray = [[]];?>


You don't create a 2d array in PHP, not in the traditional sense.

The suggestions above about $a = array(array()); in fact simply creating the following array:

$a = array(    0 => array( ));

Therefore, $a[0][0] = 'test'; would result in the following:

$a = array(    0 => array(        0 => 'test'    ));

At a first glance, it looks like it works, but in fact, this is still not a 2d array.When you try to use the 2nd row (index 1), at this point, PHP would throw a notice. Eg:

$a[1][0] = 'test2';

This is because $a[1] does not contain anything (remember that array(array()) simply creating an array at index 0?).

For it to work, you need to yet again do $a[1] = array();, or if you want to avoid indices you can do, $a[] = array();.


Example

$a = array(); // array of columnsfor($c=0; $c<5; $c++){    $a[$c] = array(); // array of cells for column $c    for($r=0; $r<3; $r++){        $a[$c][$r] = rand();    }}

The above code creates a 5x3 "2d array" of random numbers.


The PHP documentation is always a good way to start for these kind of basic questions.

<?php$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));echo $arr["somearray"][6];    // 5echo $arr["somearray"][13];   // 9echo $arr["somearray"]["a"];  // 42?>