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, like the results of a query? For this, you use arrays. Arrays are a special kind of variable that store 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

When working with arrays, there are 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 identifies the element by 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 selects 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.

Warning

Be careful, since most people tend to start counting ...

Get Learning PHP and MySQL 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.