tags:

views:

187

answers:

5

Like :

declare int d[0..m, 0..n]
+11  A: 

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);
David Caunt
+1  A: 

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.

Amber
+2  A: 

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]';
Atli
+3  A: 

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));
}
cletus
Don't you mean "arrays _of_ arrays", instead of "arrays _or_ arrays"?
Asaph
@Asaph: yes I did. Fixed. Thanks.
cletus
Good solution cletus
David Caunt
Setting up an array of zeroes is a completely pointless exercise. You don't need to declare an array, just use it.
DisgruntledGoat
Except if you need to **iterate** over it or determine it's size like if you're say doing matrix multiplication. There is a perfectly valid case for filling the array values.
cletus
+3  A: 

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.

porneL
Except that tells you nothing about the dimensions. If you're declaring an M x N 2D array, chances are it's a matrix and if it's a matrix chances are you'll be doing multiplication or something on it that will necessitate iterating over the elements, which you can't do if it's "sparse" and don't know the dimensions.
cletus
@cletus: you can just use `count` on the right dimension though, e.g. `count($d[1])`, unless I'm misunderstanding your point?
DisgruntledGoat
Still, PHP does not have multi-dimensional arrays. The possibility will always exit that an array of arrays might be sparse. So, how about making a class that implements a matrix using arrays, at least then you would take more care of proper implementation.
Don