declare array in laravel blade shuffle it and traverse it

In Laravel Blade, you can declare an array directly in the view, shuffle it using Laravel’s collect() helper (or PHP’s native shuffle()), and then loop through it with @foreach.

Here’s an example:

@php
    // Declare the array
    $items = ['Apple', 'Banana', 'Cherry', 'Mango', 'Orange'];

    // Shuffle using Laravel collection helper
    $items = collect($items)->shuffle();
@endphp

<ul>
    @foreach($items as $item)
        <li>{{ $item }}</li>
    @endforeach
</ul>

Alternative (using native PHP shuffle):

@php
    $items = ['Apple', 'Banana', 'Cherry', 'Mango', 'Orange'];
    shuffle($items); // modifies array in place
@endphp

<ul>
    @foreach($items as $item)
        <li>{{ $item }}</li>
    @endforeach
</ul>

Tips:

  • collect($array)->shuffle() is nice if you’re already using Laravel collections, and it returns a new shuffled collection without modifying the original.
  • shuffle($array) changes the original array directly.



Leave a Reply