pull(&$array, $key, $default = null)
The pull
helper method is similar to the get
(covered in the Laravel Array Helper Function: array_get article) method in that it will return a value for the given $key
in the $array
(or the $default
, if it is specified and the $key
does not exists). The difference is that the pull
method will remove the item it finds from the array.
#Mutable Function
This function affects the original $array
.
Consider the following array, which is probably familiar to most people these days:
1<?php
2
3$weekDays = [
4 1 => 'Sunday',
5 2 => 'Monday',
6 3 => 'Tuesday',
7 4 => 'Wednesday',
8 5 => 'Thursday',
9 6 => 'Friday',
10 7 => 'Saturday'
11];
A lot of people do not like Mondays. Let's demote Monday
to the $theWorstDayOfTheWeek
while also removing it from our $weekDays
:
1<?php
2
3use Illuminate\Support\Arr;
4
5// Demote 'Monday'
6$worstDayOfTheWeek = Arr::pull($weekDays, 2);
The $weekDays
array would now look like this:
1array(6) {
2 [1] "Sunday"
3 [3] "Tuesday"
4 [4] "Wednesday"
5 [5] "Thursday"
6 [6] "Friday"
7 [7] "Saturday"
8}
#array_pull(&$array, $key, $default = null)
The array_pull
function is a shortcut to calling Arr::pull
. This function is declared in the global namespace.
∎