Creating Arrays

By default, arrays are lists of values indexed by number. Values can be assigned to an array in two ways: with the array() construct or directly using empty square brackets ([]). You’ll meet both of these in the next two sections.

Defining Arrays with the array() Construct

The array() construct is useful when you want to assign multiple values to an array at one time. Let’s define an array called $users and assign four strings to it:

$users = array ("Bert", "Sharon", "Betty", "Harry");

You can now access the third element in the $user array by using the index 2:

print $users[2];

This would return the string Betty. The index of an array element is placed between square brackets directly after the array name. You can use this ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition 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.