Chapter 4. Working with Arrays

In This Chapter

  • Creating one-dimensional arrays

  • Making the most of multidimensional arrays

  • Using foreach loops to simplify array management

  • Breaking 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. Any time you're thinking about a list of things, an array is the natural way to represent this list.

Using One-Dimensional Arrays

The most basic array is a one-dimensional array, which is basically just one container with slots. 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 ...

Get HTML, XHTML, & CSS All-in-One For Dummies®, 2nd 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.