Insert an element into a PHP array at a specific position

/**
 * Inserts an element into an array at a specific position.
 *
 * @see https://wpcodebook.com/php-insert-element-array-position/
 * @see https://www.php.net/manual/en/function.array-splice.php
 *
 * @param array $array The input array.
 * @param mixed $element Added element(s). Can be a single value or an array of values.
 * @param int $position The offset from the beginning of the $array.
 *
 * @return array The resulting array.
 */
function wpcodebook_array_insert( $array, $element, $position ) {
	array_splice( $array, $position, 0, $element );
	return $array;
}

Examples

Input #1

$array    = array( 'banana', 'peach' );
$element  = array( 'apple', 'pear' );
$position = 1;

Output #1

Array
(
    [0] => banana
    [1] => apple
    [2] => pear
    [3] => peach
)

Input #2

$array    = array( 'banana', 'peach' );
$element  = 'apple';
$position = 1;

Output #2

Array
(
    [0] => banana
    [1] => apple
    [2] => peach
)

Leave a Comment