O'Reilly logo

Learning PHP & MySQL, 2nd Edition by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Arrays

Variables are great for storing a single piece of information, but what happens when you need to store data for a whole set of information, such as the results of a query? When this happens, use arrays. Arrays are a special kind of variable that stores many pieces of data. Arrays allow you to access any of the values stored in them individually yet still copy and manipulate the array as a whole. Because they are so useful, you'll see arrays used frequently. PHP provides many functions for performing common array tasks such as counting, sorting, and looping through the data.

Array Fundamentals

To work with arrays, you need to learn two new terms: elements and indexes. Elements are the values that are stored in the array. Each element in the array is referenced by an index that differentiates the element from any other unique element in the array. The index value can be a number or a string, but it must be unique. You can think of an array like a spreadsheet or a database that has only two columns. The first column uniquely identifies the row in the spreadsheet, while the second column contains a stored value.

Associative Versus Numeric Indexed Arrays

Numeric arrays use numbers as their indexes, while associative arrays use stings. When using associative arrays, you must supply an index string each time you add an element. Numeric arrays allow you to just add the element, and PHP automatically assigns the first free number, starting at 0. Both types of arrays allow you ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required