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.

Here’s how to randomize the order of the days of the week:<br />

$days = array('Monday', 'Tuesday', 'Wednesday',<br />

'Thursday', 'Friday', 'Saturday', 'Sunday');<br />

shuffle($days);<br />

print_r($days);<br />

Array<br />

(<br />

[0] => Tuesday<br />

[1] => Thursday<br />

[2] => Monday<br />

[3] => Friday<br />

[4] => Wednesday<br />

[5] => Saturday<br />

[6] => Sunday<br />

)<br />

Obviously, the order after your shuffle( ) may not be the same as the sample output<br />

here. Unless you are interested in getting multiple random elements from an array,<br />

without repeating any specific item, using the rand( ) function to pick an index is<br />

more efficient.<br />

Acting on Entire Arrays<br />

<strong>PHP</strong> has several useful functions for modifying or applying an operation to all elements<br />

of an array. You can merge arrays, find the difference, calculate the total, and<br />

more, all using built-in functions.<br />

Calculating the Sum of an Array<br />

The array_sum( ) function adds up the values in an indexed or associative array:<br />

$sum = array_sum(array);<br />

For example:<br />

$scores = array(98, 76, 56, 80);<br />

$total = array_sum($scores);<br />

// $total = 310<br />

Merging Two Arrays<br />

The array_merge( ) function intelligently merges two or more arrays:<br />

$merged = array_merge(array1, array2 [, array ... ])<br />

If a numeric key from an earlier array is repeated, the value from the later array is<br />

assigned a new numeric key:<br />

$first = array('hello', 'world'); // 0 => 'hello', 1 => 'world'<br />

$second = array('exit', 'here'); // 0 => 'exit', 1 => 'here'<br />

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

// $merged = array('hello', 'world', 'exit', 'here')<br />

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

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

Acting on Entire Arrays | 135

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

Saved successfully!

Ooh no, something went wrong!