Apr
11
2009

Handy PHP function to insert an array into another array at a specific position

I guess the code says it all.

/**
* Insert array into another array after the specified *KEY*
* @param array $array     The array.
* @param array $insert     The array to insert.
* @param mixed $after     The key to insert after
*/
function array_insert_after( $array, $insert, $after ) {
// Find the offset of the element to insert after.
$keys = array_keys($array);
$offsetByKey = array_flip( $keys );

$offset = $offsetByKey[$after];

// Insert at the specified offset
$before = array_slice( $array, 0, $offset + 1, true );
$after = array_slice( $array, $offset + 1, count($array)-$offset, true );

$output = $before + $insert + $after;

return $output;
}

posted in Uncategorized by andrew

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by openark.org