Jump to content

Archived

This topic is now archived and is closed to further replies.

448191

[solved] Array composition

Recommended Posts

I might be overlooking something obvious, but I don't see it right now..

I have a numeric array from which I want to compose a new associative array, with every first value as an index, the second as the value.

Share this post


Link to post
Share on other sites
LOL, never mind...

[url=http://nl3.php.net/manual/en/function.array-combine.php]array_combine[/url]


Share this post


Link to post
Share on other sites
Hmmm... It's still a bit too bulky I feel:

[code]<?php
function is_odd($var)
{
  return($var & 1);
}
$arr = array('key1','value1','key2','value2');
$keys = array_flip(array_filter(array_flip($arr), 'is_odd'));
$values = array_diff($arr,$keys);
$arr = array_combine($keys,$values);
?>[/code]

Share this post


Link to post
Share on other sites
[code]<?php
$res = array();
$arr = array('key1','value1','key2','value2');
$arr2 = array_chunk($arr,2);
foreach ($arr2 as $a) {$res[$a[0]] = $a[1];}

?>[/code]

Share this post


Link to post
Share on other sites
Thanks!  :)

End result:
[code]<?php
function array_compose($arr){
$arr2 = array_chunk($arr,2);
foreach($arr2 as $a){
$res[$a[0]] = next($a);
}
return $res;
}
$arr = array('key1','value1','key2','value2','emptyindex');
print_r(array_compose($arr));
?>[/code]

Outputs:
[quote]Array
(
    [key1] => value1
    [key2] => value2
    [emptyindex] =>
)[/quote]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.