note 87042 added to function.array-walk

From: Date: Sun, 16 Nov 2008 17:04:08 +0000
Subject: note 87042 added to function.array-walk
Groups: php.notes 
Request: Send a blank email to php-notes+get-146596@lists.php.net to get a copy of this message
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So? Prototype: bool arrayWalk(array &$arry, callback $callback, mixed $params=false) <?php function arrayWalk(&$arry, $callback, $params=false) { $P=array(""); // parameters $a=""; // arguement string :) if($params !== false) { // add parameters if(is_array($params)) { // multiple additional parameters foreach($params as $par) { $P[]=$par; } } else // just one additional { $P[]=$params; } } for( // create the arguement string $i=0; isset($P[$i]); ++$i ) { $a.='$'.chr($i + 97).', '; } // random argument names $a=substr($a, 0, -2); // to get rid of the last comma and two spaces $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function if(is_callable($func)) { for( // cycle through array $i=0; isset($arry[$i]); ++$i ) { $P[0]=$arry[$i]; // first element must be the first argument - array value $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function } } else { return false; } // failure - function not callable return true; // success! } // arrayWalk() ?> One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires. So, still some work left... ---- Server IP: 91.185.195.14 Probable Submitter: 89.212.132.190 ---- Manual Page -- http://www.php.net/manual/en/function.array-walk.php Edit -- https://master.php.net/note/edit/87042 Del: integrated -- https://master.php.net/note/delete/87042/integrated Del: useless -- https://master.php.net/note/delete/87042/useless Del: bad code -- https://master.php.net/note/delete/87042/bad+code Del: spam -- https://master.php.net/note/delete/87042/spam Del: non-english -- https://master.php.net/note/delete/87042/non-english Del: in docs -- https://master.php.net/note/delete/87042/in+docs Del: other reasons-- https://master.php.net/note/delete/87042 Reject -- https://master.php.net/note/reject/87042 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#146596) next »