note 56897 added to function.array-walk

From: Date: Mon, 19 Sep 2005 01:03:11 +0000
Subject: note 56897 added to function.array-walk
Groups: php.notes 
Request: Send a blank email to php-notes+get-95385@lists.php.net to get a copy of this message
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array: <? function enumerate( &$item1, $key, &$startNum ) { $item1 = $startNum++ ." $item1"; } $num = 1; $fruits = array( "lemon", "orange", "banana", "apple"); array_walk($fruits, 'enumerate', $num ); print_r( $fruits ); echo '$num is: '. $num ."\n"; ?> This outputs: Array ( [0] => 1 lemon [1] => 2 orange [2] => 3 banana [3] => 4 apple ) $num is: 1 Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter.. <? $num = 1; $fruits = array( "lemon", "orange", "banana", "apple"); array_walk($fruits, 'enumerate', &$num ); // reference here print_r( $fruits ); echo '$num is: '. $num ."\n"; echo "we've got ". ($num - 1) ." fruits in the basket!"; ?> This outputs: Array ( [0] => 1 lemon [1] => 2 orange [2] => 3 banana [3] => 4 apple ) $num is: 5 we've got 4 fruits in the basket! Now $num has changed so we are able to count the items (without calling count() unnecessarily). As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want. ---- Manual Page -- http://www.php.net/manual/en/function.array-walk.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+56897 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56897&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+56897&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#95385) next »