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 :::

diversions :::

45+ Amazing Insect Shots in Photography
Insects are one of the most fascinating creatures on earth. There are more than 800, 000 species of insects in the world.
Grayscale color | Stroep Blog
This is how I create a grayscale color in actionscript 3.
Google Flash API
This is great ... google has made this easy ... stay tuned to see what i am working on ...
25 Free Mac Apps That Will Boost Your Productivity
There are many applications that can help you work faster and efficiently. Though, not many applications come cheap.
you still want more »