PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

4.1 Introduction

Arrays are lists: lists of people, lists of sizes, lists of books. To store a group of related items in a variable, use an array. Like a list on a piece of paper, the elements in array have an order. Usually, each new item comes after the last entry in the array, but just as you can wedge a new entry between a pair of lines already in a paper list, you can do the same with arrays in PHP.

In many languages, there is only one type of array: what is called a numerical array (or just an array). In a numerical array, if you want to find an entry, you need to know its position within the array, known as an index. Positions are identified by numbers: they start at 0 and work upwards one by one.

In some languages, there is also another type of array: an associative array , also known as a hash. In an associative array, indexes aren't integers, but strings. So, in a numerical array of U.S. presidents, "Abraham Lincoln" might have index 16; in the associative-array version, the index might be "Honest." However, while numerical arrays have a strict ordering imposed by their keys, associative arrays frequently make no guarantees about the key ordering. Elements are added in a certain order, but there's no way to determine the order later.

In a few languages, there are both numerical and associative arrays. But, usually the numerical array $presidents and the associative array $presidents are distinct arrays. Each array type has a specific behavior, and you need to operate on them accordingly. PHP has both numerical and associative arrays, but they don't behave independently.

In PHP, numerical arrays are associative arrays, and associative arrays are numerical arrays. So, which kind are they really? Both and neither. The line between them constantly blurs back and forth from one to another. At first, this can be disorienting, especially if you're used to rigid behavior, but soon you'll find this flexibility an asset.

To assign multiple values to an array in one step, use array( ):

$fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');

Now, the value of $fruits[2] is 'Cantaloupes'.

array( ) is very handy when you have a short list of known values. The same array is also produced by:

$fruits[0] = 'Apples';
$fruits[1] = 'Bananas';
$fruits[2] = 'Cantaloupes';
$fruits[3] = 'Dates';

and:

$fruits[ ] = 'Apples';
$fruits[ ] = 'Bananas';
$fruits[ ] = 'Cantaloupes';
$fruits[ ] = 'Dates';

Assigning a value to an array with an empty subscript is shorthand for adding a new element to the end of the array. So, PHP looks up the length of $fruits and uses that as the position for the value you're assigning. This assumes, of course, that $fruits isn't set to a scalar value, such as 3, and isn't an object. PHP complains if you try to treat a nonarray as an array; however, if this is the first time you're using this variable, PHP automatically converts it to an array and begins indexing at 0.

An identical feature is the function array_push( ) , which pushes a new value on top of the array stack. However, the $foo[ ] notation is the more traditional PHP style; it's also faster. But, sometimes, using array_push( ) more accurately conveys the stack nature of what you're trying to do, especially when combined with array_pop( ) , which removes the last element from an array and returns it.

So far, we've placed integers and strings only inside arrays. However, PHP allows you to assign any data type you want to an array element: booleans, integers, floating-point numbers, strings, objects, resources, NULL, and even other arrays. So, you can pull arrays or objects directly from a database and place them into an array:

while ($row = mysql_fetch_row($r)) {
    $fruits[ ] = $row;
}

while ($obj = mysql_fetch_object($s)) {
    $vegetables[ ] = $obj;
}

The first while statement creates an array of arrays; the second creates an array of objects. See Recipe 4.3 for more on storing multiple elements per key.

To define an array not using integer keys but string keys, you can also use array( ), but specify the key/value pairs with =>:

$fruits = array('red' => 'Apples', 'yellow' => 'Bananas', 
                'beige' => 'Cantaloupes', 'brown' => 'Dates');

Now, the value of $fruits['beige'] is 'Cantaloupes'. This is shorthand for:

$fruits['red'] = 'Apples';
$fruits['yellow'] = 'Bananas';
$fruits['beige'] = 'Cantaloupes';
$fruits['brown'] = 'Dates';

Each array can only hold one unique value for each key. Adding:

$fruits['red'] = 'Strawberry';

overwrites the value of 'Apple'. However, you can always add another key at a later time:

$fruits['orange'] = 'Orange';

The more you program in PHP, the more you find yourself using associative arrays instead of numerical ones. Instead of creating a numeric array with string values, you can create an associative array and place your values as its keys. If you want, you can then store additional information in the element's value. There's no speed penalty for doing this, and PHP preserves the ordering. Plus, looking up or changing a value is easy because you already know the key.

The easiest way to cycle though an array and operate on all or some of the elements inside is to use foreach:

$fruits = array('red' => 'Apples', 'yellow' => 'Bananas', 
                'beige' => 'Cantaloupes', 'brown' => 'Dates');

foreach ($fruits as $color => $fruit) {
    print "$fruit are $color.\n";
}
Apples are red.
Bananas are yellow.
Cantaloupes are beige.
Dates are brown.

Each time through the loop, PHP assigns the next key to $color and the key's value to $fruit. When there are no elements left in the array, the loop finishes.

To break an array apart into individual variables, use list( ):

$fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');

list($red, $yellow, $beige, $brown) = $fruits;
    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    4.1 Introduction
    Recipe 4.2 Specifying an Array Not Beginning at Element 0
    Recipe 4.3 Storing Multiple Elements per Key in an Array
    Recipe 4.4 Initializing an Array to a Range of Integers
    Recipe 4.5 Iterating Through an Array
    Recipe 4.6 Deleting Elements from an Array
    Recipe 4.7 Changing Array Size
    Recipe 4.8 Appending One Array to Another
    Recipe 4.9 Turning an Array into a String
    Recipe 4.10 Printing an Array with Commas
    Recipe 4.11 Checking if a Key Is in an Array
    Recipe 4.12 Checking if an Element Is in an Array
    Recipe 4.13 Finding the Position of an Element in an Array
    Recipe 4.14 Finding Elements That Pass a Certain Test
    Recipe 4.15 Finding the Largest or Smallest Valued Element in an Array
    Recipe 4.16 Reversing an Array
    Recipe 4.17 Sorting an Array
    Recipe 4.18 Sorting an Array by a Computable Field
    Recipe 4.19 Sorting Multiple Arrays
    Recipe 4.20 Sorting an Array Using a Method Instead of a Function
    Recipe 4.21 Randomizing an Array
    Recipe 4.22 Shuffling a Deck of Cards
    Recipe 4.23 Removing Duplicate Elements from an Array
    Recipe 4.24 Finding the Union, Intersection, or Difference of Two Arrays
    Recipe 4.25 Finding All Element Combinations of an Array
    Recipe 4.26 Finding All Permutations of an Array
    Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele