Chapter 5. Working with Arrays
In This Chapter
Creating one-dimensional arrays
Making the most of multidimensional arrays
Using
foreach
loops to simplify array managementBreaking a string into an array
In time, arrays will become one of the most important tools in your toolbox. They can be a bit hard to grasp for beginners, but don't let that stop you. Arrays are awesome because they allow you to quickly apply the same instructions to a large number of items.
In PHP, an array is a variable that holds multiple values that are mapped to keys. Think of a golfing scorecard. You have several scores, one for each hole on the golf course. The hole number is the key, and the score for that hole is the value. Keys are usually numeric, but values can be any type. You can have an array of strings, numbers, or even objects.
Using One-Dimensional Arrays
The most basic array is a one-dimensional array. It's just one container with slots, and each slot has only one variable in it. In this section, you find out how to create this type of array and fill it.
Creating an array
Array creation is pretty simple. First, you need to create a variable and then tell PHP that you want that variable to be an array:
$theVar = array();
Now, $theVar
is an array. However, it's an empty array waiting for you to come along and fill it.
Note
Technically, you can skip the variable creation step. It's still a good idea to explicitly define an array because it helps you remember the element is an array, and there are a few special ...
Get HTML, XHTML, and CSS All-In-One Desk Reference For Dummies® 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.