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]
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));
}
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' => 'john@example.com'
),
1 => array(
'name' => 'Jane Doe',
'email' => 'jane@example.com'
),
);
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 john@example.com
. field 0 is John Doe
. field 1 is john@example.com
hi element 1
. name is Jane Doe
. email is jane@example.com
. field 0 is Jane Doe
. field 1 is jane@example.com
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.
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' => 'john@example.com'
),
1 => array(
'name' => 'Jane Doe',
'email' => 'jane@example.com'
),
);
Which is equivalent to
$array = array();
$array[0] = array();
$array[0]['name'] = 'John Doe';
$array[0]['email'] = 'john@example.com';
$array[1] = array();
$array[1]['name'] = 'Jane Doe';
$array[1]['email'] = 'jane@example.com';
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.
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'
]
]
]