Skip to content

Instantly share code, notes, and snippets.

@ZacharyDraper
Forked from scribu/array_insert.php
Last active May 8, 2017 04:18
Show Gist options
  • Save ZacharyDraper/dbdc856305f0a79fa97b2ce9fb9923a2 to your computer and use it in GitHub Desktop.
Save ZacharyDraper/dbdc856305f0a79fa97b2ce9fb9923a2 to your computer and use it in GitHub Desktop.
array_insert()
<?php
/**
* Insert an array into another array before/after a certain key
*
* @param array $array The initial array
* @param array $pairs The array to insert
* @param string $key The certain key
* @param string $position Wether to insert the array before or after the key
* @return array
*/
function array_insert( $array, $pairs, $key, $position = 'after' ) {
$key_pos = array_search( $key, array_keys( $array ) );
if ( 'after' == $position )
$key_pos++;
if ( false !== $key_pos ) {
$result = array_slice( $array, 0, $key_pos, true );
$result = $result + $pairs;
$result = $result + array_slice( $array, $key_pos, null, true );
}
else {
$result = $array + $pairs;
}
return $result;
}
@ZacharyDraper
Copy link
Author

After some minor modification, the original function by scribu now maintains array keys, allowing it to work with associative arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment