Laravel add Array Element at First Position

In this example, We will show how to use laravel add array element at first position. Laravel provide many array helpers function. Laravel arr:prepend() function to you can add array element at first position.

 Example: Laravel add Array Element in First Position using arr::prepend()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Arr;

class UserController extends Controller
{
    public function index(){        
        $array1 = ['Desk', 'Table', 'Chair'];

        $prepended1 = Arr::prepend($array1,'Basket');
        print_r($prepended1);
        //['Desk', 'Table', 'Chair','Basket']

        $array2 = ['php', 'laravel', 'html','css'];

        $prepended2 = Arr::prepend($array2,'Vue');
        print_r($prepended1);
        //['php', 'laravel', 'html','css','Vue']
    }
}

Laravel arr prepend() output

['Desk', 'Table', 'Chair','Basket']
['php', 'laravel', 'html','css','Vue']

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class,'index']);

I hope you understand laravel add array element at first position and it can help you…

Read Also :  Laravel Arr wrap() function Example