Created
July 15, 2019 10:44
-
-
Save harddy/7a01ecb1277e77a2700aa08b78edc457 to your computer and use it in GitHub Desktop.
PHP - Insert a new element after a specific key/value pair
This file contains hidden or 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 a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended | |
* to the end of the array. | |
* | |
* @param array $array | |
* @param string $key | |
* @param array $new | |
* | |
* @return array | |
*/ | |
function array_insert_after( array $array, $key, array $new ) { | |
$keys = array_keys( $array ); | |
$index = array_search( $key, $keys ); | |
$pos = false === $index ? count( $array ) : $index + 1; | |
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) ); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment