gecko by alan r.
30 January 2007

use array_map to wrap php functions

Sometimes I want to call a particular function on an array or just a single element. For example trimming whitespace on start and beginning of text (”trim“) ... I had to loop over the array and call trim on that element … array_map to the rescue…

I am using trim to show how it is used, but almost anything can be used (both built in or your own function)...

starting code

.
$my_text = '    one';
$my_array = array('   one ',' two ',' three ');
//.
//.
/** let's trim **/
$my_text = trim($my_text);
for($i = 0;$i < sizeof($my_array); $i++) {
     $my_array[i] = trim($my_array[i]);
}
//results...
//$my_text = 'one';
//$my_array = array('one','two','three');

Seems simple enough … but what i really want is to do this:

.
$my_text = '    one';
$my_array = array('   one ',' two ',' three ');
//.
//.
/** let's trim **/
$my_text  = trim($my_text);
$my_array = trim($my_array);
//results...
//$my_text = 'one';
//$my_array = array();

so that didn’t work, so array_map to the rescue …

.
$my_text = '    one';
$my_array = array('   one ',' two ',' three ');
//.
//.
/** let's trim **/
$my_text  = trim($my_text);
$my_array = array_map('trim',$my_array);
//results...
//$my_text = 'one';
//$my_array = array('one','two','three');

sweet, but i don’t want to decide myself when to call trim and when to call array_map … hence a tiny wrapper function …

.
//wrap function calls
function wrap_function($in,$function)
{
	if(is_array($in))
	{
		return array_map($function,$in);
	}
	else 
	{
		return $function($in);
	}
}

and voila! ...

.
$my_text = '    one';
$my_array = array('   one ',' two ',' three ');
//.
//.
/** let's trim **/
$my_text  = wrap_function($my_text,'trim');
$my_array = wrap_function($my_array,'trim');
//results...
//$my_text = 'one';
//$my_array = array('one','two','three');

So using this simple wrapping function you can call ALL kinds of functions … addslashes, stripslashes, mysql_escape_string

 

comment



note: you can only submit after you hit preview


nuff-respec is a weblog written by daniel bulli a senior web programmer in boston, ma.
more >

contact | resume | profile | twitter

recently :::