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

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.