How do I declare a two dimensional 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]';
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));
}