Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating Multidimensional Arrays

So far, we've been using only one-dimensional arrays, with only one set of keys. However, arrays with multiple sets of keys are also possible, and sometimes you need them. You might, for example, store test scores for various students like this:

$test_scores["Frank"] = 95;
$test_scores["Mary"] = 87;

But what if you gave a second test? You can add a second index to stand for the test number; here's what that might look like:

<?php
    $test_scores["Frank"][1] = 95;
    $test_scores["Frank"][2] = 85;
    $test_scores["Mary"][1] = 87;
    $test_scores["Mary"][2] = 93;
    print_r($test_scores);
?>

Now $test_scores["Frank"][1] is Frank's test score on the first test, $test_scores["Frank"][2] is his score on the second test, and so on. This script displays the new multidimensional array with print_r:

[Frank] => Array
    (
         [1] => 95
         [2] => 85
    )

[Mary] => Array
    (
         [1] => 87
         [2] => 93
    )

You can access individual elements using both indexes, like this:

echo "Frank's first test score is ", $test_scores["Frank"][1], "\n";

Want to interpolate an array item in double quotes? Enclose it in curly braces (and use single quotes for any text keys to avoid conflict with the double quotes):

echo "Frank's first test score is {$test_scores['Frank'][1]}\n";

You can also use the flowing syntax to create multidimensional arrays—but note that this will start the arrays off at an index value of 0:

<?php
    $test_scores["Frank"][] = 95;
    
   $test_scores["Frank"][] = 85;
    
   $test_scores["Mary"][] = 87;
    
   $test_scores["Mary"][] = 93;
    print_r($test_scores);
?>

In PHP, multidimensional arrays can be thought of as arrays of arrays. For example, a two-dimensional array may be considered as a single-dimensional array where each element is a single-dimensional array. Here's an example:

<?php
    $test_scores = array("Frank" => array(95, 85), "Mary" => array(87, 93));
    print_r($test_scores);
?>

This is what the results look like:

[Frank] => Array
    (
         [0] => 95
         [1] => 85
    )

[Mary] => Array
    (
         [0] => 87
         [1] => 93
    )

What if you wanted to start the array at index 1 instead of 0? You could do this:

<?php
    $test_scores = array("Frank" => array(1 => 95, 2 => 85),
        "Mary" => array(1 => 87, 2 => 93));
    print_r($test_scores);
?>

And here's what you would get:

[Frank] => Array
    (
         [1] => 95
         [2] => 85
    )

[Mary] => Array
    (
         [1] => 87
         [2] => 93
    )
  • + Share This
  • 🔖 Save To Your Account