PHP 8.5.0 Alpha 2 available for testing

Voting

: zero plus seven?
(Example: nine)

The Note You're Voting On

peterzuzek AT gmail DOT com
16 years ago
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...

<< Back to user notes page

To Top