How to create a multidimensional array in php?

by raul_reichert , in category: PHP , 2 years ago

How to create a multidimensional array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emely , 2 years ago

@raul_reichert You can create a multidimensional array in php using either short syntax [] or array(), here is my example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

// Multidimensional Array
$array = [
    "kevin" => [
        "age" => 21,
        "city" => "Los Angeles"
    ],
    "steven" => [
        "age" => 22,
        "city" => "Chicago"
    ]
];

Member

by violette , a year ago

@raul_reichert 

To create a multidimensional array in PHP, you can use the array function with multiple sets of square brackets. For example:

1
2
3
4
5
$multi_array = array(
  array(1, 2, 3),
  array(4, 5, 6),
  array(7, 8, 9)
);


This creates a 3x3 multidimensional array with the values 1 through 9. You can access elements of the array using multiple sets of square brackets as well. For example, to access the value 5 from the array above, you would use $multi_array[1][1].


You can also use the short array syntax introduced in PHP 5.4 to create multidimensional arrays:

1
2
3
4
5
$multi_array = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];


If you need to create a multidimensional array with a set number of rows and columns, you can use nested loops to initialize the array. For example:

1
2
3
4
5
6
7
8
9
$rows = 3;
$cols = 3;

$multi_array = array();
for ($i = 0; $i < $rows; $i++) {
  for ($j = 0; $j < $cols; $j++) {
    $multi_array[$i][$j] = 0;
  }
}


This creates a 3x3 multidimensional array with all elements initialized to 0.