Creating Arrays

You can create an array using either the array() function or the array operator []. The array() function is usually used when you want to create a new array and populate it with more than one element at the same time. The array operator is used when you want to create a new array with just one element (for now), or when you want to add to an existing element.

The following code snippet shows how to create an array called $rainbow, containing all its various colors:

$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo", "violet");

The following snippet shows the same array being created incrementally using the array operator:

 $rainbow[] = "red"; $rainbow[] = "orange"; $rainbow[] = "yellow"; $rainbow[] = "green"; ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One 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.