Insert an element at the beginning of an array in PHP

/**
 * Inserts an element at the beginning of an array.
 *
 * @see https://wpcodebook.com/php-insert-element-beginning-array/
 * @see https://www.php.net/manual/en/function.array-unshift.php
 */
array_unshift( $array, $element );

Example:

$array = array( 'green', 'blue' );
array_unshift( $array, 'red' );
print_r( $array );

Output:

Array
(
    [0] => red
    [1] => green
    [2] => blue
)

Leave a Comment