PHP Multidimensional Array.

PHPServer Side ProgrammingProgramming

Definition and Usage

A multidimensional array in PHP an be treated as an array of arrays so that each element within the array is an array itself. Inner elements of a multi dimensional array may be associative or indexed.

Although arrays can be nested upto any levels, two dimensional array with more than one dimensional arrays inside outermost is of realistic use

Syntax

//two dimensional associative array
twodim = array(
   "row1"=>array(k1=>v1,k2=>v2,k3=>v3),
   "row2"=>array(k4=>v4,k5=>v5,k6=>v6)
)
//two dimensional indexed array
twodim=array(
   array(v1,v2,v3),
   array(v4,v5,v6)
)

In case of indexed two dimensional array, we can access an element from the array by its index with following syntax:

$arr[row][column];

PHP Version

Use of square brackets for assignment of array is available since PHP 5.4

Following example shows indexed 2D array in which each element is an indexed array

Example

 Live Demo

<?php
$arrs=array(
   array(1,2,3,4,5),
   array(11,22,33,44,55),
);
foreach ($arrs as $arr){
   foreach ($arr as $i){
      echo $i . " ";
   }
   echo "\n";
}
$cols=count($arrs[0]);
$rows=count($arrs);
for ($i=0; $i<$rows; $i++){
   for ($j=0;$j<$cols;$j++){
      echo $arrs[$i][$j] . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

1 2 3 4 5
11 22 33 44 55
1 2 3 4 5
11 22 33 44 55

Following example has indexed 2D array whaving associative arrays as element

Example

 Live Demo

<?php
$arrs=array(
   array(1=>100, 2=>200, 3=>300),
   array(1=>'aa', 2=>'bb', 3=>'cc'),
);
foreach ($arrs as $arr){
   foreach ($arr as $i=>$j){
      echo $i . "->" .$j . " ";
   }
   echo "\n";
}
for ($row=0; $row < count($arrs); $row++){
   foreach ($arrs[$row] as $i=>$j){
      echo $i . "->" .$j . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

1->100 2->200 3->300
1->aa 2->bb 3->cc

1->100 2->200 3->300
1->aa 2->bb 3->cc
}

In following example we have an associative two dimensional array:

Example

 Live Demo

<?php
$arr1=array("rno"=>11,"marks"=>50);
$arr2=array("rno"=>22,"marks"=>60);
$arrs=array(
   "Manav"=>$arr1,
   "Ravi"=>$arr2
);
foreach ($arrs as $key=>$val){
   echo "name : " . $key . " ";
   foreach ($val as $i=>$j){
      echo $i . "->" .$j . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

name : Manav rno->11 marks->50
name : Ravi rno->22 marks->60

This Example has associative array with each value as indexed array

Example

 Live Demo

<?php
$arr1=array("PHP","Java","Python");
$arr2=array("Oracle","MySQL","SQLite");
$arrs=array(
   "Langs"=>$arr1,
   "DB"=>$arr2
);
foreach ($arrs as $key=>$val){
   echo $key . ": ";
   for ($i=0; $i < count($val); $i++){
      echo $val[$i] . " ";
   }
   echo "\n";
}
?>

Output

This will produce following result −

Langs: PHP Java Python
DB: Oracle MySQL SQLite
raja
Published on 19-Sep-2020 14:46:44
Advertisements