Array manipulation with most commonly used Laravel collection methods

In PHP development, efficient array manipulation is a must in many applications. Laravel, one of the most popular PHP frameworks, offers a powerful tool for handling arrays: Collections. Collections extend PHP's native array functions and provide additional functionality to simplify array manipulation tasks. It offers a wide range of methods for filtering, sorting, mapping, reducing, and more, making common array operations more expressive and concise.

In this blog post, we'll explore Laravel Collection methods and demonstrate how they ease array manipulation with practical examples.

To begin using Laravel Collections, we need to convert an array into a Collection using the collect() helper function. Once data is wrapped in a Collection object, we gain access to a various array manipulation methods.

Let's dive into some practical examples. We first create a index() method inside HomeController and then paste this following code to see the example code output in the browser.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    //
    function index() {
        // Sample data
        $data = [1, 2, 3, 4, 5];

        // Creating a collection
        $collection = collect($data);

        // Manipulating Arrays
        $collection->push(6);
        $collection->pop();
        $collection->shift();
        $collection->prepend(0);
        $slice = $collection->slice(1, 3);
        $collection = $collection->merge([7, 8, 9]); //dd( $collection );
        $combined = $collection->combine(['a', 'b', 'c', 'd', 'e', 'f' ,'g', 'h']);
        $diff = $collection->diff([3, 4, 5]);
        $intersect = $collection->intersect([3, 4, 5]);

        // Sorting and Searching Arrays
        $sorted = $collection->sort();
        $sortedDescending = $collection->sortDesc( );
        $searchedKey = $collection->search(3);
        $exists = $collection->contains(3);
        $keyExists = $collection->has('a');

        // Array Iteration
        $filtered = $collection->filter(function ($value, $key) {
            return $value % 2 == 0;
        });
        $walked = $collection->map(function ($item, $key) {
            return $item * 2;
        });
        $reduced = $collection->reduce(function ($carry, $item) {
            return $carry + $item;
        }, 0);

        // Manipulating Array Keys and Values
        $keys = $collection->keys();
        $values = $collection->values();
        $flipped = $collection->flip();
        $reversed = $collection->reverse();

        // Outputting results
        dd([
            'slice' => $slice->all(),
            'combined' => $combined->all(),
            'diff' => $diff->all(),
            'intersect' => $intersect->all(),
            'sorted' => $sorted->all(),
            'sortedDescending' => $sortedDescending->all(),
            'searchedKey' => $searchedKey,
            'exists' => $exists,
            'keyExists' => $keyExists,
            'filtered' => $filtered->all(),
            'walked' => $walked->all(),
            'reduced' => $reduced,
            'keys' => $keys->all(),
            'values' => $values->all(),
            'flipped' => $flipped->all(),
            'reversed' => $reversed->all(),
        ]);
    }
}

In code above, we have used various methods related to manipulation, filtering and iteration available in Collections using a sample dataset.

Now code above will spit out this following output

<?php
array:16 [// app\Http\Controllers\HomeController.php:69
  "slice" => array:3 [
    1 => 2
    2 => 3
    3 => 4
  ]
  "combined" => array:8 [
    0 => "a"
    2 => "b"
    3 => "c"
    4 => "d"
    5 => "e"
    7 => "f"
    8 => "g"
    9 => "h"
  ]
  "diff" => array:5 [
    0 => 0
    1 => 2
    5 => 7
    6 => 8
    7 => 9
  ]
  "intersect" => array:3 [
    2 => 3
    3 => 4
    4 => 5
  ]
  "sorted" => array:8 [
    0 => 0
    1 => 2
    2 => 3
    3 => 4
    4 => 5
    5 => 7
    6 => 8
    7 => 9
  ]
  "sortedDescending" => array:8 [
    7 => 9
    6 => 8
    5 => 7
    4 => 5
    3 => 4
    2 => 3
    1 => 2
    0 => 0
  ]
  "searchedKey" => 2
  "exists" => true
  "keyExists" => false
  "filtered" => array:4 [
    0 => 0
    1 => 2
    3 => 4
    6 => 8
  ]
  "walked" => array:8 [
    0 => 0
    1 => 4
    2 => 6
    3 => 8
    4 => 10
    5 => 14
    6 => 16
    7 => 18
  ]
  "reduced" => 38
  "keys" => array:8 [
    0 => 0
    1 => 1
    2 => 2
    3 => 3
    4 => 4
    5 => 5
    6 => 6
    7 => 7
  ]
  "values" => array:8 [
    0 => 0
    1 => 2
    2 => 3
    3 => 4
    4 => 5
    5 => 7
    6 => 8
    7 => 9
  ]
  "flipped" => array:8 [
    0 => 0
    2 => 1
    3 => 2
    4 => 3
    5 => 4
    7 => 5
    8 => 6
    9 => 7
  ]
  "reversed" => array:8 [
    7 => 9
    6 => 8
    5 => 7
    4 => 5
    3 => 4
    2 => 3
    1 => 2
    0 => 0
  ]
]

As we can see above, by leveraging Collections, we can perform complex array operations with ease and make our code to more cleaner and maintainable.

Related Posts


Using collection method reduce()