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 …