Using array_unshift() to Insert One or More Elements at the Beginning of an Array

This article explains PHP’s array_unshift() function, detailing its purpose, parameters, return value, and provides a complete example showing how to prepend elements to an array and the resulting output for developers seeking to manipulate array order efficiently.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_unshift() to Insert One or More Elements at the Beginning of an Array

Purpose: int array_unshift(array &$array, mixed $var, ...) inserts one or more elements at the beginning of an array. The inserted elements are treated as a whole, preserving their order, and numeric keys are reindexed starting from zero while string keys remain unchanged.

Parameters:

array : The input array to be modified.

var : One or more variables to prepend to the array.

Return value: The new number of elements in the array after the operation.

Example:

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

Output:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTutorialarray manipulationarray_unshift
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.