Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created November 7, 2015 13:04
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save wpscholar/0deadce1bbfa4adb4e4c to your computer and use it in GitHub Desktop.
Save wpscholar/0deadce1bbfa4adb4e4c to your computer and use it in GitHub Desktop.
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.
<?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 ) );
}
@edwinsnotje
Copy link

Thanks

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