• Post category:PHP

How to Create Multidimensional Array PHP | Explained

How to Create Multidimensional Array PHP

This article will show how to create a multidimensional array php with example code. A multidimensional PHP array is more than an array in which each array element is itself an array. A multidimensional array can, therefore, be considered a table, where each element in the parent array represents a row of the table and the elements of each child array represent the columns of the row. To access an element, we specify the array name and then follow it with the desired row and column of the array, each enclosed in square brackets ([]). We can have nested for or for each loop to access this multidimensional array.

Ex:
See the example of a PHP multidimensional array to display the following tabular data of a numeric array. In this example, we are displaying 3 rows and 3 columns. Here, we have printed the array using two methods:

1. for loop
2. foreach loop

<?php
//Creating Multidimensional array
$emp = array
(
array(1, "Abi", 4000),
array(2, "John", 9000),
array(3, "Ram", 45000)
);

// Printing array Method 2
for ($row = 0 ; $row<3; $row++)
{
for($col=0; $col <3; $col++)
echo $emp[$row][$col] . " ";
echo "<br/>";
}

echo "<br/>";
echo "<br/>";

// Printing array Method 2
foreach($emp as $k1){
foreach($k1 as $k2)
echo $k2. " ";
echo "<br/>";}
?>

Output:

how to create multidimensional array php

Leave a Reply