The `Arr::prepend()` method is a helper function provided by Laravel `Illuminate\Support\Arr` class that allows you to prepend an item to the beginning of an array.
Basic Usage
<?php use Illuminate\Support\Arr; $array = ['one', 'two', 'three']; $result = Arr::prepend($array, 'zero'); // Result: ['zero', 'one', 'two', 'three'] ?>
With Associative Arrays
When working with associative arrays, you can optionally specify a key for the prepended value:
<?php $array = ['name' => 'John', 'age' => 30]; $result = Arr::prepend($array, 'Doe', 'last_name'); // Result: // ['last_name' => 'Doe', 'name' => 'John', 'age' => 30] ?>
Key Features in Laravel 11.x & Laravel 12.x
1. Preservation of Keys: Numeric keys will be re-indexed, while string keys are preserved.
2. Non-destructive Operation: The original array remains unchanged (returns a new array).
3. Helper Function: Also available as the global `array_prepend()` helper function.
Edge Cases
<?php // Prepending to an empty array $result = Arr::prepend([], 'first'); // ['first'] // Prepending without a key (numeric index) $result = Arr::prepend(['a' => 'apple'], 'orange'); // [0 => 'orange', 'a' => 'apple'] ?>
This method is particularly useful when you need to add items to the beginning of an array while maintaining clean, readable code.