35

I know that arrays are created dynamically, and creating them ahead of time isn't really necessary, but how would one do that with a 2D array? The same way?

(for$j)
{
for($i)
    {
    $array[j][i] = "data";
    }
}

Something like that? Obviously real for loops, of course.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joshua
  • 4,270
  • 10
  • 42
  • 62

8 Answers8

54

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 = [[]];
?>
Brendan Bullen
  • 11,607
  • 1
  • 31
  • 40
  • 5
    @Joshua No problem. I think people downvoted because they didn't understand the reasoning behind the question. Not a good reason to downvote. That's what comments are for. Keep on asking questions... :) – Brendan Bullen Jul 07 '11 at 15:55
  • @Joshua time will reveal the truth! – windsound Dec 08 '13 at 18:09
  • Careful though, as print_r( $emptyArray ) shows it isn't truly empty (that would be hard as removing the inner [] would render it a 1D array). – Herbert Van-Vliet May 21 '21 at 16:16
24

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 columns
for($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.

Christian
  • 27,509
  • 17
  • 111
  • 155
  • I wondered where my empty entries came from when using 2-dim arrays. Changed $arr[]=array(); at top of function to $arr[$id]=array(); where it is used and all is fine again – RST Mar 03 '15 at 13:55
2

If I want to create an empty array for handling lines from text files, I just use $array = array();

2

Using "array(array())" will create a 2D array with an "empty" element in the first position. To create a truly blank 2D array this needs to be removed.

<?php
    $emptyArray = array(array());  // Creates a 2D array with one empty element in $emptyArray[0]
    array_pop($emptyArray);        // Pops element[0] off the array
?>
2

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];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>
Henrik P. Hessel
  • 36,243
  • 17
  • 80
  • 100
  • 5
    I looked at the multidimensional array documentation, there are no examples for creating an empty one. – Joshua Jul 07 '11 at 15:51
2

Could you specify what you are trying to do? You can loop through multidimensional arrays with the foreach function

$ary=array( "subarr" => array("foo","bar") );

foreach($ary as $a){
  foreach($a as $ary_sub){
    echo $ary_sub;
  }
}

or

foreach($ary["subarr"] as $key=>$subval){
 echo $subval;
}
Christian Smorra
  • 1,756
  • 11
  • 13
1
// dynamic 2D array

$twoD = array(array());
$val = 0;

// fill the array
for($r = 0; $r < 4; $r++) {
    for($c = 0; $c < 4; $c++) 
        $twoD[$r][$c] = $val++;
}

// print the current value of $val
echo $val."<br/>------------------<br/>";

// print the array  
for($r = 0; $r < 4; $r++) {
    for($c = 0; $c < 4; $c++) 
        echo $twoD[$r][$c];
    echo "<br/>";
}
Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Samcoder
  • 345
  • 1
  • 4
  • 14
0

Remember that whenever you use array(array()) nested function or the short array syntax [[]] both will create a 2D array with an empty element in the first position. This may bring you some errors so we needs to be removed it.

How we can remove an empty element?

Well it is absolute simple as calling the array_pop() method to pop the element[0] off the array, as this:

<?php
    $a = array(array());
    echo 'Before removing the empty element: \n'
    print_r($a);
    array_pop($a);
    print_r($a);

    $b = [[]];
    echo 'Before removing the empty element: \n'
    print_r($b);
    array_pop($b);
    print_r($b);
?>
Teocci
  • 7,189
  • 1
  • 50
  • 48