note 109251 added to function.array-combine

From: Date: Fri, 29 Jun 2012 15:17:53 +0000
Subject: note 109251 added to function.array-combine
Groups: php.notes 
Request: Send a blank email to php-notes+get-188971@lists.php.net to get a copy of this message
I was looking for a function to take a linear array, $array, and combine the elements into an associative array. I used the following function to wrap the behavior of array_combine() to combine odd and even elements of the original array: <?php function combineLinearArray( $arrayToSmush, $evenItemIsKey = true ) { if ( ( count($arrayToSmush) % 2 ) !== 0 ) { throw new Exception( "This array cannot be combined because it has an odd number of values" ); } $evens = $odds = array(); // Extract even values for ($i = 0, $c = count($arrayToSmush); $i < $c; $i += 2) { $evens[] = $arrayToSmush[$i]; } // Extract odd values for ($i = 1, $c = count($arrayToSmush); $i < $c; $i += 2) { $odds[] = $arrayToSmush[$i]; } // Combine them and return return ( $evenItemIsKey ) ? array_combine($evens, $odds) : array_combine($odds, $evens) ; } ?> Here is an example of usage: <?php $array = array( 'one', 1, 'two', 2, 'three', 3, 'four', 4 ); print_r( combineLinearArray($array) ); /* Prints: Array ( [one] => 1 [two] => 2 [three] => 3 [four] => 4 ) */ ?> ---- Server IP: 69.147.83.197 Probable Submitter: 173.227.191.21 ---- Manual Page -- http://www.php.net/manual/en/function.array-combine.php Edit -- https://master.php.net/note/edit/109251 Del: integrated -- https://master.php.net/note/delete/109251/integrated Del: useless -- https://master.php.net/note/delete/109251/useless Del: bad code -- https://master.php.net/note/delete/109251/bad+code Del: spam -- https://master.php.net/note/delete/109251/spam Del: non-english -- https://master.php.net/note/delete/109251/non-english Del: in docs -- https://master.php.net/note/delete/109251/in+docs Del: other reasons-- https://master.php.net/note/delete/109251 Reject -- https://master.php.net/note/reject/109251 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188971) next »