O'Reilly logo

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

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