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.

Sets<br />

Arrays let you implement the basic operations of set theory: union, intersection, and<br />

difference. Each set is represented by an array, and various <strong>PHP</strong> functions implement<br />

the set operations. The values in the set are the values in the array—the keys<br />

are not used, but they are generally preserved by the operations.<br />

The union of two sets is all the elements from both sets, with duplicates removed.<br />

The array_merge( ) and array_unique( ) functions let you calculate the union. Here’s<br />

how to find the union of two arrays:<br />

function array_union($a, $b) {<br />

$union = array_merge($a, $b); // duplicates may still exist<br />

$union = array_unique($union);<br />

return $union;<br />

}<br />

$first = array(1, 'two', 3);<br />

$second = array('two', 'three', 'four');<br />

$union = array_union($first, $second);<br />

print_r($union);<br />

Array<br />

(<br />

[0] => 1<br />

[1] => two<br />

[2] => 3<br />

[4] => three<br />

[5] => four<br />

)<br />

The intersection of two sets is the set of elements they have in common. <strong>PHP</strong>’s builtin<br />

array_intersect( ) function takes any number of arrays as arguments and returns<br />

an array of those values that exist in each. If multiple keys have the same value, the<br />

first key with that value is preserved.<br />

Another common function to perform on a set of arrays is to get the difference; that<br />

is, the values in one array that are not present in another array. The array_diff( )<br />

function calculates this, returning an array with values from the first array that are<br />

not present in the second.<br />

The following code takes the difference of two arrays:<br />

$first = array(1, 'two', 3);<br />

$second = array('two', 'three', 'four');<br />

$difference = array_diff($first, $second);<br />

print_r($difference);<br />

Array<br />

(<br />

[0] => 1<br />

[2] => 3<br />

)<br />

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

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

Using Arrays | 137

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

Saved successfully!

Ooh no, something went wrong!