Learn how to create and access PHP multidimensional arrays

multidimensional-array is an array element which can contain another array as a value, which in turn can hold other arrays as well.

Each location in the array can hold another array. multidimensional-arrays can be two-dimensional or three-dimensional array.

Example, We have this following user's table, which holds our user's information, their Usernames, E-mails and Countries of origin.

UsernameE-mailCountry
Jordanjordan@yahoo.comUSA
Beckhambeckham@gmail.comUK
Uhurukenyatauhuru@gv.keKenya

Now we need to represent our table in array using PHP.

Example ⇓ multidimensional-arrays
We will first create an array of users, which is two-dimensional.

 

    
<!DOCTYPE html>
 <html>
   <body>
   <?php
 
 
  //two-dimensional Array of users    
$users=array(
        array('Jordan','jordan@yahoo.com','USA'),
        array('Beckham','beckham@gmail.com','UK'),
        array('Uhurukenyata','uhuru@gv.ke','Kenya'),
      );
      
//We can access our array by using index  like this:-
//Let us print out the information of the user Jorden
    echo $users[0][0].'<br/>';
    echo $users[0][1].'<br/>';
    echo $users[0][2];
    
      ?>
    </body>
 </html>

Output: -
The user Jordan is stored in $users[0][0]
The user's E-mail jordan@yahoo.com is  stored in $users[0][1]
The user's country USA is stored in $users[0][2]

If you take a look at the above table, the information of Jordan is on the first row (Line) Each element has two indexes – row and column. We have used $users[0][0] to get the Username of Jorden. This means we are accessing row number (index) 0 and column number (index) 0, to get the Username Note that index numbers begin by Zero not 1

We can access the $users array data by using nested for loop like this:-

!DOCTYPE html>
 <html>
   <body>
   <?php
 
  
  echo "<ol>";
for($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";
   for($col = 0; $col < 3; $col++)
    {
        echo "<li>".$users[$row][$col]."</li>";
    }
    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
   ?>
    </body>
 </html>

output:-
1.The row number 0

• Jordan
• jordan@yahoo.com
• USA

2.The row number 1

• Beckham
• beckham@gmail.com
• UK

3.The row number 2

• Uhurukenyata
• uhuru@gv.ke
• Kenya

 

Another two dimensional array example but this time it is an Associative Array, we can access this using foreach construct.

<?php
$countries = array (
    'GERMANY' => array('Barlin', 'Frankfurt'),
    'USA' => array('Washington DC', 'New York'),
    'SOUTH AFRIKA' => array('Johannesburg    ', 'Pretoria'),
);
foreach ($countries as $key=>$country) :
      foreach ($country as $cityName) :
         print "$cityName is in $key <br/>\n";
     endforeach;
endforeach;
?>

Output:-

Barlin is in GERMANY
Frankfurt is in GERMANY
Washington DC is in USA
New York is in USA
Johannesburg is in SOUTH AFRIKA
Pretoria is in SOUTH AFRIKA