Skip to content

Instantly share code, notes, and snippets.

@jimboobrien
Forked from wpscholar/array-insert-before.php
Created September 20, 2017 22:41
Show Gist options
  • Save jimboobrien/916a51c579132762dc910bcd651d3c5b to your computer and use it in GitHub Desktop.
Save jimboobrien/916a51c579132762dc910bcd651d3c5b to your computer and use it in GitHub Desktop.
Insert a value or key/value pair before a specific key in an array. If key doesn't exist, value is prepended to the beginning of the array.
<?php
/**
* Insert a value or key/value pair before a specific key in an array. If key doesn't exist, value is prepended
* to the beginning of the array.
*
* @param array $array
* @param string $key
* @param array $new
*
* @return array
*/
public static function array_insert_before( array $array, $key, array $new ) {
$keys = array_keys( $array );
$pos = (int) array_search( $key, $keys );
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