Laravel Array Helper Function: array_fetch

November 18, 2016 —John Koster

#Deprecated

The fetch helper function has been deprecated as of Laravel 5.1 in favor of the pluck helper function. Additionally, the An Extended Example of Retrieving Unique Data Using Laravel Helper Functions article from the original publication provides other uses for Laravel's array helper functions.

The fetch helper method is used to pull data from a multi-dimensional array. The data to fetch is expressed in dot notation. Assuming the following array of students, languages and courses:

1<?php
2 
3$students = [
4 'student-001' => [
5 'first_name' => 'John',
6 'languages' => [
7 'count' => 2,
8 'names' => [
9 'French',
10 'English'
11 ]
12 ],
13 'courses' => [
14 'CIS 100',
15 'CIS 200'
16 ]
17 ],
18 'student-002' => [
19 'first_name' => 'Jane',
20 'languages' => [
21 'count' => 2,
22 'names' => [
23 'Spanish',
24 'English'
25 ]
26 ],
27 'courses' => [
28 'CIS 100',
29 'CIS 200'
30 ]
31 ],
32 'student-003' => [
33 'first_name' => 'Jim',
34 'courses' => [
35 'HUMA 1302'
36 ]
37 ]
38 ];

we could fetch the names of all the courses like so:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$courses = Arr::fetch($students, 'courses');

which return the following array:

1array(3) {
2 [0] array(2) {
3 [0] "CIS 100"
4 [1] "CIS 200"
5 }
6 [1] array(2) {
7 [0] "CIS 100"
8 [1] "CIS 200"
9 }
10 [2] array(1) {
11 [0] "HUMA 1302"
12 }
13}

Accessing the count value within the languages array can be done using dot notation:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$languageCounts = Arr::fetch($students, 'languages.count');

which would return this array:

1array(2) {
2 [0] 2
3 [1] 2
4}

When an array key is specified that does not exist in one of the nested arrays, no value is returned. That is why there is only two student language counts in the above array when there are three students.

Accessing all the languages spoken by the students could be done like so:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$languages = Arr::fetch($students, 'languages.names');

which would return the following result:

1array(2) {
2 [0] array(2) {
3 [0] "French"
4 [1] "English"
5 }
6 [1] array(2) {
7 [0] "Spanish"
8 [1] "English"
9 }
10}

#array_fetch($array, $key)

The array_fetch function is a shortcut to calling Arr::fetch. This function is declared in the global namespace. This helper function was removed in Laravel 5.1.

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.