HOW to insert a value or key/value pair before a specific key in an array

There is a case when you require to add a value or key/value pair before a specific key in an array.

Here’s the simple PHP function which you can use to achieve this. If the key doesn’t exist, value is prepended to the beginning of the array

/**
	 * 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 ) );
	}
Scroll to Top