-
-
Save georgejipa/9ce9121c353c5be5b491b1e3272d60e8 to your computer and use it in GitHub Desktop.
array_insert()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
$result = array_merge( $result, $pairs ); | |
$result = array_merge( $result, array_slice( $array, $key_pos ) ); | |
} | |
else { | |
$result = array_merge( $array, $pairs ); | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment