Mask
Mask

Reputation: 34197

How do I declare a two dimensional array?

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]

Upvotes: 104

Views: 383504

Answers (16)

LuxuryHagama
LuxuryHagama

Reputation: 11

Very late for the party, but for anyone searching this nowadays - if you want to simply declare a bidimensional array like you would in c# simply declare it in the scope as follows:

<?php
  $My2dArray = array(array());
  //This allows you to use it as a bidimensional array. See this loop for example:
  for($i = 0; $i < 5; $i++) {
    $My2dArray[$i]["whatever-you-want"] = "MyValue";
  }
  
  return $My2dArray;
?>

Upvotes: -1

Detlef Lindenthal
Detlef Lindenthal

Reputation: 45

//  You can define your 2D array like this ...
$numbers = [[1, 2], [3, 4]];

// ... or for Questions and Answers 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    )   )   */

Upvotes: 0

mmateas
mmateas

Reputation: 50

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.

Upvotes: 0

Denis Ivanov
Denis Ivanov

Reputation: 1

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));

Upvotes: 0

James Burnett
James Burnett

Reputation: 171

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' => '[email protected]'
    ),
    1 => array(
        'name' => 'Jane Doe',
        'email' => '[email protected]'
    ),
);

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 [email protected]
. field 0 is John Doe
. field 1 is [email protected]
hi element 1
. name is Jane Doe
. email is [email protected]
. field 0 is Jane Doe
. field 1 is [email protected]

Upvotes: 7

Minwork
Minwork

Reputation: 1022

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

Upvotes: -1

Oskar
Oskar

Reputation: 2562

And I like this way:

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

Upvotes: 1

Deshal Kh
Deshal Kh

Reputation: 253

$r = array("arr1","arr2");

to echo a single array element you should write:

echo $r[0];
echo $r[1];

output would be: arr1 arr2

Upvotes: 1

user824232
user824232

Reputation: 83

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.

Upvotes: 2

Ray
Ray

Reputation: 41428

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:

     $final_array = array(array(array(), array(), array()), array(array(), array(), array()), array(array(), array(), array()));

...etc...

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.

Upvotes: 3

Kingsolmn
Kingsolmn

Reputation: 1858

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.

Upvotes: 14

cletus
cletus

Reputation: 625057

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));
}

Upvotes: 29

Kornel
Kornel

Reputation: 100110

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.

Upvotes: 51

Atli
Atli

Reputation: 7930

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

Upvotes: 96

Amber
Amber

Reputation: 526583

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.

Upvotes: 11

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58361

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);

Upvotes: 71

Related Questions