note 108200 added to control-structures.foreach

From: Date: Fri, 06 Apr 2012 20:21:45 +0000
Subject: note 108200 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-186998@lists.php.net to get a copy of this message
<?php // LIMITATION: YOU CANNOT PASS THE $key BY REFERENCE USING PHP'S NATIVE foreach ($array as $key => &$value) CONTROL STRUCTURE // SOLUTION: USE ArrayUtil::ForEachFn(Array &$array, $fn) // ADDITIONAL BENEFIT: // 1 - YOU DON'T HAVE TO WORRY ABOUT THE FOLLOWING WARNING: // Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). // PHP 5 >= 5.3.0 // EXAMPLE OF LIMITATION foreach ($array as &$key => &$value) { // YOUR CODE HERE } unset($value) // break the reference with the last element // THE ABOVE EXAMPLE WILL OUTPUT: // Fatal error: Key element cannot be a reference in... // SOLUTION (FOR YOU TO COPY) class ArrayUtil { public static function ForEachFn(Array &$array, $fn) { $newArray = array(); foreach ($array as $key => $value) { $fn($key, $value); $newArray[$key] = $value; } $array = $newArray; } } // EXAMPLE CALLBACK $fn = function (&$key, &$value) { // NOTE THE FUNCTION'S SIGNATURE (USING & FOR BOTH $key AND $value) if ($key === 'key2') { $key = 'BY REF KEY EXAMPLE'; // THIS IS THE WHOLE POINT OF THIS POST } if ($value === 'value2') { $value = 'BY REF VALUE EXAMPLE'; } }; // EXAMPLE USAGE $array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ); print_r($array); ArrayUtil::ForEachFn($array, $fn); print_r($array); /* THE ABOVE "EXAMPLE USAGE" OUTPUTS: Array ( [key1] => value1 [key2] => value2 [key3] => value3 ) Array ( [key1] => value1 [BY REF KEY EXAMPLE] => BY REF VALUE EXAMPLE [key3] => value3 ) */ ---- Server IP: 69.147.83.197 Probable Submitter: 76.169.174.129 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/108200 Del: integrated -- https://master.php.net/note/delete/108200/integrated Del: useless -- https://master.php.net/note/delete/108200/useless Del: bad code -- https://master.php.net/note/delete/108200/bad+code Del: spam -- https://master.php.net/note/delete/108200/spam Del: non-english -- https://master.php.net/note/delete/108200/non-english Del: in docs -- https://master.php.net/note/delete/108200/in+docs Del: other reasons-- https://master.php.net/note/delete/108200 Reject -- https://master.php.net/note/reject/108200 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186998) next »