PHP

๐Ÿ“ฅ PHP array_unshift() Function: Prepending Elements to Arrays

The array_unshift() function in PHP prepends one or more elements to the beginning of an array. All existing numerical keys are re-indexed to start counting from zero, while literal keys remain untouched.

  • Return Value: array_unshift() modifies the source array directly (passed by reference) and returns the new total number of elements in the array.

๐Ÿ› ๏ธ Basic Syntax & Usage

You can insert a single element or multiple values separated by commas to the start of an array:

PHP
$colors = ["Green", "Blue"];

// Prepending a single element
array_unshift($colors, "Red");

// Prepending multiple elements at once
array_unshift($colors, "Yellow", "Orange");

print_r($colors);
/*
Output:
Array
(
    [0] => Yellow
    [1] => Orange
    [2] => Red
    [3] => Green
    [4] => Blue
)
*/

โšก Parameter Order & Multi-Element Insertion

When passing multiple elements, array_unshift() prepends them together as a block so their original relative order is preserved at the beginning of the array.

PHP
$numbers = [3, 4];

// Elements are inserted in the specified order: 1 then 2
array_unshift($numbers, 1, 2);

print_r($numbers);
// Result: [1, 2, 3, 4]

๐Ÿ“‹ Key Rules & Behaviors

  • 1. Index Reset: All numerical indexes are updated to start from 0. Associative keys (string keys) will maintain their key-value associations without changes.
  • 2. Direct Mutation: The target array is passed by reference (&$array), meaning the original array is altered directly.
  • 3. Type Requirement: The target parameter must be a valid array variable; otherwise, a TypeError is thrown in PHP 8+.

๐Ÿ“Š Insertion Functions Comparison

Function Target Position Numeric Key Behavior Return Value
array_push() End of array Appends next auto-increment integer New total element count
array_unshift() Beginning of array Re-indexes all numeric keys from 0 New total element count
  • ๐Ÿ“ Short Summary

  • array_unshift() adds one or more elements to the front of an array.
  • It automatically re-indexes numerical keys starting from 0.
  • The source array is modified directly and the updated total count is returned.