Skip to content

Instantly share code, notes, and snippets.

@kendru
Created June 29, 2012 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kendru/3018733 to your computer and use it in GitHub Desktop.
Save kendru/3018733 to your computer and use it in GitHub Desktop.
Combine linear array into associative array in PHP
<?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();
// Separate even and odd values
for ($i = 0, $c = count($arrayToSmush); $i < $c; $i += 2) {
$evens[] = $arrayToSmush[$i];
$odds[] = $arrayToSmush[$i+1];
}
// Combine them and return
return ( $evenItemIsKey ) ? array_combine($evens, $odds) : array_combine($odds, $evens);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment