PHP: How to Create a Multidimensional Array

PHP: How to Create a Multidimentional Array?

In PHP, a multi-dimensional array can be created by nesting arrays. For example, to create a 2-dimensional array with 2 rows and 3 columns, you can use the following code:

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

You can also use a loop to create a multi-dimensional array of a specific size, like this:

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

In this example, $multiArray is a multi-dimensional array. You can access its elements like this:

$element = $multiArray[0][1];

Note that, arrays in php are zero indexed which means the first element of an array is at the position "0"

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.