Skip to Main Content
Learning PHP, MySQL, and JavaScript
book

Learning PHP, MySQL, and JavaScript

by Robin Nixon
July 2009
Beginner content levelBeginner
526 pages
14h 24m
English
O'Reilly Media, Inc.
Content preview from Learning PHP, MySQL, and JavaScript

Multidimensional Arrays

A simple design feature in PHP’s array syntax makes it possible to create arrays of more than one dimension. In fact, they can be as many dimensions as you like (although it’s a rare application that goes further than three).

And that feature is the ability to include an entire array as a part of another one, and to be able to keep on doing so, just like the old rhyme: “Big fleas have little fleas upon their backs to bite ’em. Little fleas have lesser fleas, add flea, ad infinitum.”

Let’s look at how this works by taking the associative array in the previous example and extending it—see Example 6-10.

Example 6-10. Creating a multidimensional associative array
<?php
$products = array(
    'paper' =>     array(
        'copier' => "Copier & Multipurpose",
        'inkjet' => "Inkjet Printer",
        'laser'  => "Laser Printer",
        'photo'  => "Photographic Paper"),

    'pens' => array(
        'ball'   => "Ball Point",
        'hilite' => "Highlighters",
        'marker' => "Markers"),

    'misc' => array(
        'tape'   => "Sticky Tape",
        'glue'   => "Adhesives",
        'clips'  => "Paperclips") );

echo "<pre>";
foreach ($products as $section => $items)
    foreach ($items as $key => $value)
        echo "$section:\t$key\t($value)<br>";
echo "</pre>";
?>

To make things clearer now that the code is starting to grow, I’ve renamed some of the elements. For example, seeing as the previous array $paper is now just a subsection of a larger array, the main array is now called $products. Within this array there are three items: paper, pens, and misc, and each of these ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Web Database Applications with PHP and MySQL, 2nd Edition

Web Database Applications with PHP and MySQL, 2nd Edition

Hugh E. Williams, David Lane
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 9780596803605Supplemental ContentErrata Page