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.
As far as I'm aware there is no built in php function to do this, you need to do it via a loop or via a custom method that recursively calls to something like array_fill inidcated in the answer by @Amber;
I'm assuming you mean created an empty but intialized array of arrays. For example, you want a final results like the below of a array of 3 arrays:
$final_array = array(array(), array(), array());
This is simple to just hand code, but for an arbitrary sized array like a an array of 3 arrays of 3 arrays it starts getting complex to initialize prior to use:
I get the frustration. It would be nice to have an easy way to declare an initialized array of arrays any depth to use without checking or throwing errors.
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
To get the first item from the array, you'll use $arr[0][0], that's like the first item from the first array from the array.
$arr[1][0] will return the first item from the second array from the array.
// You can define your 2D array like this ...
$QaA = [
['Question_1', 'Answer_1'],
['Question_2', 'Answer_2'] ];
// ... and return some very value like this ...
echo $QaA[1][1]; // "Answer_2"
// And you can browse through all this 2D array:
foreach ( $QaA as $nr1 => $content ) {
echo "\n";
foreach ($content as $nr2 => $answer) {
echo " $nr1, $nr2: $answer"; } }
/* Result:
0, 0: Question_1 0, 1: Answer_1
1, 0: Question_2 1, 1: Answer_2 */
// Thus you can see all the array:
print_r($QaA); /* Result:
Array (
[0] => Array (
[0] => Question_1
[1] => Answer_1 )
[1] => Array (
[0] => Question_2
[1] => Answer_2 ) ) */