05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If a string key from an earlier array is repeated, the earlier value is replaced by the<br />

later value:<br />

$first = array('bill' => 'clinton', 'tony' => 'danza');<br />

$second = array('bill' => 'gates', 'adam' => 'west');<br />

$merged = array_merge($first, $second);<br />

// $merged = array('bill' => 'gates', 'tony' => 'danza', 'adam' => 'west')<br />

Calculating the Difference Between Two Arrays<br />

The array_diff( ) function identifies values from one array that are not present in<br />

others:<br />

$diff = array_diff(array1, array2 [, array ... ]);<br />

For example:<br />

$a1 = array('bill', 'claire', 'elle', 'simon', 'judy');<br />

$a2 = array('jack', 'claire', 'toni');<br />

$a3 = array('elle', 'simon', 'garfunkel');<br />

// find values of $a1 not in $a2 or $a3<br />

$diff = array_diff($a1, $a2, $a3);<br />

// $diff is array('bill', 'judy');<br />

Values are compared using ===, so1and "1" are considered different. The keys of the<br />

first array are preserved, so in $diff the key of 'bill' is 0 and the key of 'judy' is 4.<br />

Filtering Elements from an Array<br />

To identify a subset of an array based on its values, use the array_filter( ) function:<br />

$filtered = array_filter(array, callback);<br />

Each value of array is passed to the function named in callback. The returned array<br />

contains only those elements of the original array for which the function returns a<br />

true value. For example:<br />

function is_odd ($element) {<br />

return $element % 2;<br />

}<br />

$numbers = array(9, 23, 24, 27);<br />

$odds = array_filter($numbers, 'is_odd');<br />

// $odds is array(0 => 9, 1 => 23, 3 => 27)<br />

As you see, the keys are preserved. This function is most useful with associative<br />

arrays.<br />

Using Arrays<br />

Arrays crop up in almost every <strong>PHP</strong> program. In addition to their obvious use for<br />

storing collections of values, they’re also used to implement various abstract data<br />

types. In this section, we show how to use arrays to implement sets and stacks.<br />

136 | Chapter 5: Arrays<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!