Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered array to associative array, odd values as keys

Pretty straightforward:

// turn
array('foo', 'bar', 'hello', 'world');

// into
array('foo' => 'bar', 'hello' => 'world');

Right now I'm using:

do{
    $arrayOut[current($arrayIn)] = next($arrayIn);
}while(next($arrayIn));

I'm wondering if there's a way to do it without the intermediary variable, $arrayOut. I could write a function, however this is a single use case, and I'm trying to keep my script uncluttered. I'm just wondering if there's something I missed in the docs that would serve this purpose.


The values are coming from a routing path:

route/to/controller/action/key1/value1/key2/value2

It's exploded, and eventually after using the other components, I'm left with ('key1', 'value1', 'key2', 'value2', ...)


Thank you folks for the insight and suggestions. Long Ears won this one for the concise approach, which when expanded to more than "1 line", is not terribly cryptic (I don't think at least)

However, also with regard to Long Ears' suggestion, perhaps my desire for semantically precise code with minimal verbosity has gotten the better of me, and I was chasing daisies trying to keep my variable scope "pollutant-free", to paraphrase myself.

like image 503
Dan Lugg Avatar asked Dec 21 '22 16:12

Dan Lugg


2 Answers

You can make your existing code slightly more efficient (removes one function call per iteration, for one at the beginning:)

$b = array();
array_unshift($a, false);
while (false !== $key = next($a)) {
    $b[$key] = next($a);
}

Ok, (shudder) here's your one liner:

$b = call_user_func_array('array_merge', array_map(function($v) { return array($v[0] => $v[1]); }, array_chunk($a, 2)));
like image 91
Long Ears Avatar answered Jan 11 '23 16:01

Long Ears


You do not need an array, you can do it directly with the path text:

$path = "foo/bar/hello/world";

preg_match_all("#(?J)(?<key>[^/]+)/(?<val>[^/]*)#", $path, $p);
$params = array_combine($p['key'], $p['val']);

print_r($params);
/*
Array
(
    [foo] => bar
    [hello] => world
)
*/
like image 36
Giovanni Mesquita Avatar answered Jan 11 '23 17:01

Giovanni Mesquita