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