How do I declare a two dimensional array?
Question
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]
Popular Answer
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]';
Read more... Read less...
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);
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.
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));
}
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 <= ∞ (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.
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
.