Advertisement
Advertisement


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]
2019/06/25
1
91
6/25/2019 10:25:48 AM


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);
2009/11/28

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.

2009/11/28

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));
}
2009/11/28

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.

2011/11/19

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.

2009/11/28

Source: https://stackoverflow.com/questions/1811100
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]