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.

Calling a Function for Each Array Element<br />

<strong>PHP</strong> provides a mechanism, array_walk( ), for calling a user-defined function once<br />

per element in an array:<br />

array_walk(array, function_name);<br />

The function you define takes in two or, optionally, three arguments: the first is the<br />

element’s value, the second is the element’s key, and the third is a value supplied to<br />

array_walk( ) when it is called. For instance, here’s another way to print table columns<br />

made of the values from an array:<br />

function print_row($value, $key) {<br />

print("$value$key\n");<br />

}<br />

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');<br />

array_walk($person, 'print_row');<br />

A variation of this example specifies a background color using the optional third<br />

argument to array_walk( ). This parameter gives us the flexibility we need to print<br />

many tables, with many background colors:<br />

function print_row($value, $key, $color) {<br />

print("$value$key\n");<br />

}<br />

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');<br />

array_walk($person, 'print_row', 'blue');<br />

The array_walk( ) function processes elements in their internal order.<br />

Reducing an Array<br />

A cousin of array_walk( ), array_reduce( ), applies a function to each element of the<br />

array in turn, to build a single value:<br />

$result = array_reduce(array, function_name [, default ]);<br />

The function takes two arguments: the running total, and the current value being<br />

processed. It should return the new running total. For instance, to add up the<br />

squares of the values of an array, use:<br />

function add_up ($running_total, $current_value) {<br />

$running_total += $current_value * $current_value;<br />

return $running_total;<br />

}<br />

$numbers = array(2, 3, 5, 7);<br />

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

// $total is now 87<br />

The array_reduce( ) line makes these function calls:<br />

add_up(2,3)<br />

add_up(13,5)<br />

add_up(38,7)<br />

128 | 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!