PHP Free Tutorial

Two Dimensional Arrays in PHP

In PHP, Programming by Baqir Ali

In PHP, two-dimensional arrays are arrays within arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. Two- dimensional arrays store data in the form of a table, For example, a two-dimensional array called $Students could contain the names of Students and the thesis topic. Below is a grid that represents such a two-dimensional array.

NameThesis 1Thesis 2
Baqir AliWireless CommunicationAndroid Mobile Application
Elia HaiderVoIP in Python Human-Computer Interaction
Dabeer HaiderProfessional Issues in ComputingData Science

Example 1: Implementing the above table in PHP Code as a two-dimensional array and display it via loop within an HTML table.

<?php
$Students = array( 
	         array('Baqir Ali','Wireless Comm', 'AM Application'), 
	         array('Elia Haider','VoIP in Python','Human-Computer Interaction'), 
	         array('Dabeer Haider','Professional Issues in Computing','Data Science')
	         );
?>
<table border="1">
<?php
    foreach($Students as $std)
    {
        echo "<tr>"; 
        foreach($std as $item)
        {
             echo "<td>$item</td>";
        }
        echo "</tr>";
     }
?>
</table>

Output:

two dimensional array in php

Example 2: Printing each element of two dimensional array using index values:

<?php

	$list=array(array(1,2,3,4,5,6,7,8,9,10),array(11,12,13,14,15,16,17,18,19,20));

		echo $list[1][4];
		echo "<br>";
		echo $list[1][6];
		echo "<br>";
		echo $list[0][4];

?>

Output:

15
17
5

Example 3: Printing each element of two-dimensional array using nested for loop

<?php
 $list=array(array(1,2,3,4,5,6,7,8,9,10),array(11,12,13,14,15,16,17,18,19,20));
		for($i=0; $i<=1; $i++)
		{
			for($j=0; $j<10; $j++)
			{
				echo $list[$i][$j];
				echo " ";
			}
				echo "<br>";
		}

?>

Output:

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20

Example 4: Printing each element of a two-dimensional array using a foreach loop.

<?php

$list=array(array(1,2,3,4,5,6,7,8,9,10),array(11,12,13,14,15,16,17,18,19,20));

		foreach($list as $numbers)
		{
			foreach($numbers as $num)
			{
				echo "$num ";
			}
			echo "<br>";
		}

?>

Output:

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20

Finding the size of Multi-dimensional Arrays

<?php


	$plants = array('perennials' =>array('Day Lilies', 'Coral Bells', 'Goldenrod', 'Russian Sage'),'annuals' =>array('Begonia', 'Sweet Alyssum', 'Cosmos', 'Helioptrope'));

    echo "The number of elements: ",
    count($plants, COUNT_RECURSIVE),"\n<br />";//output 10 
    echo	"The	number	of	arrays:	",	count($plants), "\n<br/>"; // output 2

?>

The number of elements: 10
The number of arrays: 2

Support us by sharing this post