Question

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

Was it helpful?

Solution

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

OTHER TIPS

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')));

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));

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 user187291's workaround looks far simpler.

Have you tried passing in the variables by Reference.

trimAll(&$a,&$b,&$c)

This works, but uses call-time pass-by-reference, which is deprecated in PHP 5.3:

function trimAll() {
    $backtrace = debug_backtrace();
    foreach($backtrace[0]['args'] as &$arg)
        if(isset($arg) && is_string($arg))
            $arg=trim($arg);
}
$a='  aaa ';
$b='  bbb ';
$c='  ccc ';
trimAll(&$a,&$b,&$c);
echo "$a\n";
echo "$b\n";
echo "$c\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top