Saturday, August 18, 2012

PHP array_walk any function

Built-in array_walk  function of PHP require a specially defined functions to work with. So any built-in functions or your other functions can not walk on array. Below code provide a functionality to overcome this issue and walk any function on your array. 
$my_arr=array("a"=>"apple","b"=>"banana","c"=>'cashew');

//walker function holder array
$GLOBALS['walker']="";

/**
 * walker walks a function over an array
 */
function array_walk_(&$array,$function,$var=array()){
   $GLOBALS['walker']=$function;
   array_walk($array,'walk_helper',$var);
}

/**
 * Helper function for the walker
 */
function walk_helper(&$item,$key,$var=null){
   $var[]=$item;
   $item=call_user_func_array($GLOBALS['walker'],$var);
}

array_walk_($my_arr,'strtoupper');
print_r($my_arr);

array_walk_($my_arr,'strtolower');
print_r($my_arr);            


Result of the execution:

Array ( [a] => APPLE [b] => BANANA [c] => CASHEW ) Array ( [a] => apple [b] => banana [c] => cashew )

No comments:

Post a Comment