views:

81

answers:

5

I saw another post suggesting using this statement to trim string variables contained in the array:

$_POST=array_map('trim', $_POST);

However, if in the first place, the strings are not contained in an array, I would like to have a trim function that can be used like this:

$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll($a,$b,$c); //arbitrary number of string variables can be passed

I tried to write a function like this:

function trimAll() {

    $args = &func_get_args();
    foreach($args as &$arg) {
        if(isset($arg) && is_string($arg))
            $arg=&trim($arg);
    }
      //no return value is required
}

But without success, the string variables do not get trimmed after function return.

Why and how can this be done??

A: 

Have you tried passing in the variables by Reference.

trimAll(&$a,&$b,&$c)
Toby Allen
Call-time pass-by-reference (what you suggest) is deprecated in PHP 5.
ken
@ken thank you so much for your information
bobo
I know its depreciated, but is it not also about the only way he can do what he wants unless there is a way of declaring that all (unknown number of) properties of a method will be passed byref
Toby Allen
+1  A: 

I don't think you can pass a variable-length list of args by reference.

You could pass in an array of references.

function trimAll($array) {
    foreach($array as $k => $v) {
        if(isset($array[$k]) && is_string($array[$k]))
            $array[$k]=&trim($array[$k]);
    }
}

... and suitably modify your call to create an array of references.

$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll(array(&$a,&$b,&$c));
martin clayton
alex
lemon
It won't, it complains Fatal error: Only variables can be passed by reference on line 15http://codepad.org/FItzMVjn
bobo
Call-time pass-by-reference (what you suggest) is deprecated in PHP 5.
ken
maybe I should adopt approach's stereofrog
bobo
+4  A: 

you cannot pass variable number of parameters by reference. As a workaround, try something like

list($a, $b, $c) = array_map('trim', array($a, $b, $c));

better yet, rewrite the snippet so that it doesn't require to use a bunch of variables, which is a bad idea anyways

stereofrog
+1  A: 

I'm not convinced that this is possible using func_get_args, though a comment on it's PHP manual page suggests one possible alternative solution: http://uk3.php.net/manual/en/function.func-get-args.php#90095

However stereofrog's workaround looks far simpler.

PeterJCLaw
+1  A: 

This also works, but will likely make anyone you might happen to work with frustrated as its very unintuitive:

// pass variables by string name
extract(array_map('trim', compact('a', 'b', 'c')));
ken