5.1. Single-Dimensional Arrays

To refer to an element of an array, you use square brackets. Inside the brackets you put the index of the element, as in Listing 5.1. This construct may be treated exactly like a variable. You may assign a value or pass its value to a function. You do not have to declare anything about the array before you use it. Like variables, any element of an array will be created on the fly. If you refer to an array element that does not exist, it will evaluate to be zero or an empty string depending on the context.

Listing 5.1. Referencing array elements
<?php
    $Cities[0] = "San Francisco";
    $Cities[1] = "Los Angeles";
    $Cities[2] = "New York";
    $Cities[3] = "Martinez";

    print("I live in $Cities[3].<br>\n");
?>

Single-dimensional ...

Get Core PHP Programming, 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.