Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Arrays

To model our surroundings accurately in a programming environment, we need to recognize that some types of data naturally group together. Colors, for example, naturally clump together into one group. Rather than having hundreds of separate variables—one for each color—it makes more sense to have one variable that holds a list, or array, of colors.

First Steps

PHP has built-in support for arrays of data, and you can create them using the array() function or using a special operator, [ ].

There are two things you need to understand before continuing:

  • An array is a normal PHP variable, but it works like a container—you can put other variables inside it.

  • Each variable inside an array is called an element. Each element has a key and a value, which can be any other variable.

Here is a basic example:

    $myarray = array("Apples", "Oranges", "Pears");
    $size = count($myarray);
    print_r($myarray);

On the first line, we see the most basic way to create an array, the array() function. This takes a series of variables or values as its parameters (you can pass no parameters to get an empty array, or as many as you want), and returns an array containing those variables. In that example, $myarray contains three elements . Line two contains a new function, count(), that returns the number of elements existing in the array passed to it.

Line three contains another new function, print_r(). This takes just one parameter, but it outputs detailed information about a variable, such as its type, length, and ...

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

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page