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.

The default argument, if provided, is a seed value. For instance, if we change the call<br />

to array_reduce( ) in the previous example to:<br />

$total = array_reduce($numbers, 'add_up', 11);<br />

The resulting function calls are:<br />

add_up(11,2)<br />

add_up(13,3)<br />

add_up(16,5)<br />

add_up(21,7)<br />

If the array is empty, array_reduce( ) returns the default value. If no default value is<br />

given and the array is empty, array_reduce( ) returns NULL.<br />

Searching for Values<br />

The in_array( ) function returns true or false, depending on whether the first argument<br />

is an element in the array given as the second argument:<br />

if (in_array(to_find, array [, strict])) { ... }<br />

If the optional third argument is true, the types of to_find and the value in the array<br />

must match. The default is to not check the types.<br />

Here’s a simple example:<br />

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

'root@example.com');<br />

$got_spam = in_array('spam@cyberpromo.net', $addresses); // $got_spam is true<br />

$got_milk = in_array('milk@tucows.com', $addresses); // $got_milk is false<br />

<strong>PHP</strong> automatically indexes the values in arrays, so in_array( ) is much faster than a<br />

loop that checks every value to find the one you want.<br />

Example 5-2 checks whether the user has entered information in all the required<br />

fields in a form.<br />

Example 5-2. Searching an array<br />

<br />

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

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

Traversing Arrays | 129

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

Saved successfully!

Ooh no, something went wrong!