ChrisJJ
ChrisJJ

Reputation: 2292

Workaround for no array_map for keys and values

I'd like a function that fills an array from a callback supplying key and value, to looplessly refactor e.g. this:

 foreach(array_slice($argv,1) as $arg)
 if( preg_match('~^([^=]*)=([^=]*)$~',$arg,$matches)) $_SERVER[$matches[1]] = $matches[2];

What's the nearest available?

Upvotes: 1

Views: 192

Answers (2)

Orangepill
Orangepill

Reputation: 24645

Probably the easiest way to do this would be to use array_walk to walk the array and apply the results to the superglobal.

array_walk(array_slice($argv,1), function ($val) {
    list($key, $value) = explode("=", $val, 2);
    if (isset($value){
         $_SERVER[$key] = $value;
    }
});

If you had wanted to do something like this targeting a non super global you would just need to add use (&$array) after the function keyword in the callback.

Upvotes: 0

deceze
deceze

Reputation: 522165

$_SERVER += array_reduce(array_slice($argv, 1), function (array $args, $arg) {
    return $args + preg_match('~^([^=]*)=([^=]*)$~', $arg, $m) ? [$m[1] => $m[2]] : [];
}, []);

Whether this is really anymore sensible than a straight foreach loop is very debatable, but hey...

Upvotes: 2

Related Questions