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. Link to comment https://forums.phpfreaks.com/topic/20801-solved-array-composition/ 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] Link to comment https://forums.phpfreaks.com/topic/20801-solved-array-composition/#findComment-92077 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] Link to comment https://forums.phpfreaks.com/topic/20801-solved-array-composition/#findComment-92087 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] Link to comment https://forums.phpfreaks.com/topic/20801-solved-array-composition/#findComment-92100 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] Link to comment https://forums.phpfreaks.com/topic/20801-solved-array-composition/#findComment-92106 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.