448191 Posted September 14, 2006 Share Posted September 14, 2006 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. Quote Link to comment Share on other sites More sharing options...
448191 Posted September 14, 2006 Author Share Posted September 14, 2006 LOL, never mind...[url=http://nl3.php.net/manual/en/function.array-combine.php]array_combine[/url] Quote Link to comment Share on other sites More sharing options...
448191 Posted September 15, 2006 Author Share Posted September 15, 2006 Hmmm... It's still a bit too bulky I feel:[code]<?phpfunction 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] Quote Link to comment Share on other sites More sharing options...
Barand Posted September 15, 2006 Share Posted September 15, 2006 [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] Quote Link to comment Share on other sites More sharing options...
448191 Posted September 15, 2006 Author Share Posted September 15, 2006 Thanks! :)End result:[code]<?phpfunction 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] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.