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.

4
  • 5
    an empty 2 dimensional array... $array = array(array()); Commented Jul 7, 2011 at 15:45
  • That way seems correct, if you're sure you want to fill the array with an empty string n*m times. Commented Jul 7, 2011 at 15:45
  • 3
    I don't know what the deal with the downvotes are. I looked and could not find the answer, so I asked it. Pardon me for trying to learn how to use php. Commented Jul 7, 2011 at 15:51
  • 1
    upvoted your comment back to 0 :) Commented Jul 7, 2011 at 15:58

8 Answers 8

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 = [[]];
?>
Sign up to request clarification or add additional context in comments.

3 Comments

@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... :)
@Joshua time will reveal the truth!
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).
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.

1 Comment

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
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;
}

Comments

2

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

Comments

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
?>

1 Comment

Thank you for sharing this. I thought I was going crazy trying to figure out how I created a blank element at [0]
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
?>⁠ ⁠ ⁠ ⁠ ⁠ ⁠ 

1 Comment

I looked at the multidimensional array documentation, there are no examples for creating an empty one.
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/>";
}

Comments

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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.