Search

Laravel 5: Removing Elements From an Array With forget

April 11, 2018 —John Koster

The forget helper method removes items from the given $array. The specified keys are express in dot notation.

Mutable Function

This function affects the original $array; because of this you do not have to reassign the original array value to a new variable.

#Signature

The signature of the forget method is:

1public static function forget(
2 &$array,
3 $keys
4);

#Example Use

Assuming an array is defined as follows:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$anArray = [
6 'person' => [
7 'first_name' => 'Jane',
8 'last_name' => 'Doe'
9 ]
10];

We could remove the first_name value like so:

1<?php
2 
3Arr::($anArray, 'person.first_name');

Which would leave the array as follows:

1array {
2 ["person"] array {
3 ["last_name"] "Doe"
4 }
5}

Removing multiple items at once is as simple as passing an array as the second argument:

1<?php
2 
3Arr::forget(
4 $anArray, [
5 'person.first_name',
6 'person.last_name'
7 ]);

#Global array_forget Helper Function

The array_forget function is a shortcut to calling Arr::forget. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.