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

recently :::

diversions :::

Using Flash And Staying Standards Compliant
Anyone who has ever worked with Flash on the web has likely come across the fact that embedding flash into a web page is usually no walk in the park...
A Design is Finished when...
This is probably the hardest part of designing for me.... 23 Pro designers weigh in with their opinions ...
JungleCrazy.com
Find all the Amazon.com products that are discounted by at least 70%
IETester
IETester is a free WebBrowser that allows you to have the rendering and javascript engines of IE8 beta 1, IE7 IE 6 and IE5.5 on Vista and XP, as well as the installed IE in the same process.
you still want more »