O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required