[php] How do I declare a two dimensional array?

What's the easiest way to create a 2d array. I was hoping to be able to do something similar to this:

declare int d[0..m, 0..n]

This question is related to php arrays

The answer is


If you want to quickly create multidimensional array for simple value using one liner I would recommend using this array library to do it like this:

$array = Arr::setNestedElement([], '1.2.3', 'value');

which will produce

[
  1 => [
    2 => [
      3 => 'value'
    ]
  ]
]

$r = array("arr1","arr2");

to echo a single array element you should write:

echo $r[0];
echo $r[1];

output would be: arr1 arr2


And I like this way:

$cars = array
  (
  array("Volvo",22),
  array("BMW",15),
  array("Saab",5),
  array("Land Rover",17)
  );

You need to declare an array in another array.

$arr = array(array(content), array(content));

Example:

$arr = array(array(1,2,3), array(4,5,6));

To get the first item from the array, you'll use $arr[0][0], that's like the first item from the first array from the array. $arr[1][0] will return the first item from the second array from the array.


You can also create an associative array, or a "hash-table" like array, by specifying the index of the array.

$array = array(
    0 => array(
        'name' => 'John Doe',
        'email' => '[email protected]'
    ),
    1 => array(
        'name' => 'Jane Doe',
        'email' => '[email protected]'
    ),
);

Which is equivalent to

$array = array();

$array[0] = array();
$array[0]['name'] = 'John Doe';
$array[0]['email'] = '[email protected]';

$array[1] = array();
$array[1]['name'] = 'Jane Doe';
$array[1]['email'] = '[email protected]';

For a simple, "fill as you go" kind of solution:

$foo = array(array());

This will get you a flexible pseudo two dimensional array that can hold $foo[n][n] where n <= 8 (of course your limited by the usual constraints of memory size, but you get the idea I hope). This could, in theory, be extended to create as many sub arrays as you need.


Just declare? You don't have to. Just make sure variable exists:

$d = array();

Arrays are resized dynamically, and attempt to write anything to non-exsistant element creates it (and creates entire array if needed)

$d[1][2] = 3;

This is valid for any number of dimensions without prior declarations.


atli's answer really helped me understand this. Here is an example of how to iterate through a two-dimensional array. This sample shows how to find values for known names of an array and also a foreach where you just go through all of the fields you find there. I hope it helps someone.

$array = array(
    0 => array(
        'name' => 'John Doe',
        'email' => '[email protected]'
    ),
    1 => array(
        'name' => 'Jane Doe',
        'email' => '[email protected]'
    ),
);

foreach ( $array  as $groupid => $fields) {
    echo "hi element ". $groupid . "\n";
    echo ". name is ". $fields['name'] . "\n";
    echo ". email is ". $fields['email'] . "\n";
    $i = 0;
    foreach ($fields as $field) {
         echo ". field $i is ".$field . "\n";
        $i++;
    }
}

Outputs:

hi element 0
. name is John Doe
. email is [email protected]
. field 0 is John Doe
. field 1 is [email protected]
hi element 1
. name is Jane Doe
. email is [email protected]
. field 0 is Jane Doe
. field 1 is [email protected]

Firstly, PHP doesn't have multi-dimensional arrays, it has arrays of arrays.

Secondly, you can write a function that will do it:

function declare($m, $n, $value = 0) {
  return array_fill(0, $m, array_fill(0, $n, $value));
}

You can try this, but second dimension values will be equals to indexes:

$array = array_fill_keys(range(0,5), range(0,5));

a little more complicated for empty array:

$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));


As far as I'm aware there is no built in php function to do this, you need to do it via a loop or via a custom method that recursively calls to something like array_fill inidcated in the answer by @Amber;

I'm assuming you mean created an empty but intialized array of arrays. For example, you want a final results like the below of a array of 3 arrays:

   $final_array = array(array(), array(), array());

This is simple to just hand code, but for an arbitrary sized array like a an array of 3 arrays of 3 arrays it starts getting complex to initialize prior to use:

     $final_array = array(array(array(), array(), array()), array(array(), array(), array()), array(array(), array(), array()));

...etc...

I get the frustration. It would be nice to have an easy way to declare an initialized array of arrays any depth to use without checking or throwing errors.


And for me the argument about whether an array should be sparse or not depends on the context.

For example, if $a[6][9] is not populated is the equivalent to $a[6][9] being populated with for example with "" or 0.


Or for larger arrays, all with the same value:

$m_by_n_array = array_fill(0, $n, array_fill(0, $m, $value);

will create an $m by $n array with everything set to $value.


The following are equivalent and result in a two dimensional array:

$array = array(
    array(0, 1, 2),
    array(3, 4, 5),
);

or

$array = array();

$array[] = array(0, 1, 2);
$array[] = array(3, 4, 5);