How do I declare a two dimensional array?

Viewed 351820

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]
15 Answers

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 I like this way:

$cars = array
  (
  array("Volvo",22),
  array("BMW",15),
  array("Saab",5),
  array("Land Rover",17)
  );

You need to declare an array in another array.

$arr = array(array(content), array(content));

Example:

$arr = array(array(1,2,3), array(4,5,6));

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.

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'
    ]
  ]
]

You can try this, but second dimension values will be equals to indexes:

$array = array_fill_keys(range(0,5), range(0,5));

a little more complicated for empty array:

$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));

//  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    )   )   */
Related