April 11, 2018 —John Koster
The pull
helper method is similar to the get
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.
This function affects the original $array
.
The signature of the pull
method is:
1public static function pull(2 &$array,3 $key,4 $default = null5);
Consider the following array, which is probably familiar to most people these days:
1$weekDays = [2 1 => 'Sunday',3 2 => 'Monday',4 3 => 'Tuesday',5 4 => 'Wednesday',6 5 => 'Thursday',7 6 => 'Friday',8 7 => 'Saturday'9];
A lot of people do not like Mondays. Let's demote Monday
to the $theWorstDayOfTheWeek
while also removing it from our $weekDays
:
1use Illuminate\Support\Arr;2 3// Demote 'Monday'4$worstDayOfTheWeek = Arr::pull($weekDays, 2);
The $weekDays
array would now look like this:
1array {2 [1] "Sunday"3 [3] "Tuesday"4 [4] "Wednesday"5 [5] "Thursday"6 [6] "Friday"7 [7] "Saturday"8}
array_pull
Helper FunctionThe array_pull
function is a shortcut to calling Arr::pull
. This function is declared in the global namespace.
∎
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.