05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

EXTR_PREFIX_SAME, which says that the third argument to extract( ) is a prefix for the<br />

variable names that are created. This helps ensure that you create unique variable<br />

names when you use extract( ). It is good <strong>PHP</strong> style to always use EXTR_PREFIX_SAME,<br />

as shown here:<br />

$shape = "round";<br />

$array = array("cover" => "bird", "shape" => "rectangular");<br />

extract($array, EXTR_PREFIX_SAME, "book");<br />

echo "Cover: $book_cover, Book Shape: $book_shape, Shape: $shape";<br />

Cover: bird, Book Shape: rectangular, Shape: round<br />

Creating an Array from Variables<br />

The compact( ) function is the complement of extract( ). Pass it the variable names<br />

to compact either as separate parameters or in an array. The compact( ) function creates<br />

an associative array whose keys are the variable names and whose values are the<br />

variable’s values. Any names in the array that do not correspond to actual variables<br />

are skipped. Here’s an example of compact( ) in action:<br />

$color = 'indigo';<br />

$shape = 'curvy';<br />

$floppy = 'none';<br />

$a = compact('color', 'shape', 'floppy');<br />

// or<br />

$names = array('color', 'shape', 'floppy');<br />

$a = compact($names);<br />

Traversing Arrays<br />

The most common task with arrays is to do something with every element—for<br />

instance, sending mail to each element of an array of addresses, updating each file in<br />

an array of filenames, or adding up each element of an array of prices. There are several<br />

ways to traverse arrays in <strong>PHP</strong>, and the one you choose will depend on your data<br />

and the task you’re performing.<br />

The foreach Construct<br />

The most common way to loop over elements of an array is to use the foreach<br />

construct:<br />

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');<br />

foreach ($addresses as $value) {<br />

echo "Processing $value\n";<br />

}<br />

Processing spam@cyberpromo.net<br />

Processing abuse@example.com<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Traversing Arrays | 125

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!