Back To Top

Multidimensional arrays

Example Multidimensional array that we will be working with

Array
(
    [Name] => Array
        (
            [1] => Jon
            [Brother] => Tony
            [3] => Kade
        )

    [Address] => Array
        (
            [Jon] => 11111 N 28th Dr.
            [Tony] => 2222 W Pershing Dr.
            [Kade] => 3333 W Chama
        )

    [Phone Number] => Array
        (
            [0] => 123.987.2736
            [1] => (602) 602-1111
            [2] => 911
        )

)

Output inner array with all variables

Here I am going to use a Foreach command to out put the address inner array as an ordered list.

<?php
    
echo '<ol>';
    FOREACH (
$array1['Address'] as $key => $value) {
        echo 
"<li>Name: $key <br/>Address: $value <br/><br/></li>";
    };
    echo 
'</ol>';
?>

  1. Name: Jon
    Address: 11111 N 28th Dr.

  2. Name: Tony
    Address: 2222 W Pershing Dr.

  3. Name: Kade
    Address: 3333 W Chama

Out put entier array

Here I will I out put the entier array with nested FOREACH comands. You would be able to choose how to output the information . For this example I am going to use an < ol > for the main array and an < ul > for the second level array.

<?php
    
echo '<ol>';
    FOREACH (
$array1 as $key => $array2) {
        echo 
"<li>$key<ul>";
        
        FOREACH (
$array2 as $key2 => $value2)  {
            echo 
"<li>$key2 => $value2</li>";
        };
        echo 
'</ul></li>';
    };
    echo 
'</ol>';
?>

  1. Name
    • 1 => Jon
    • Brother => Tony
    • 3 => Kade
  2. Address
    • Jon => 11111 N 28th Dr.
    • Tony => 2222 W Pershing Dr.
    • Kade => 3333 W Chama
  3. Phone Number
    • 0 => 123.987.2736
    • 1 => (602) 602-1111
    • 2 => 911