Search

Laravel 5: Conditionally Retrieving Array Values With where

April 11, 2018 —John Koster

The where helper method is functionally similar to the pluck method, in that both take a source $array and filter it to produce a smaller array. It works by iterating over each element in the $array and executing the $callback on each key value pair. If the $callback returns a value that evaluates to true, the key/value pair is kept, otherwise it is ignored when constructing the final array.

#Signature

The signature of the where method is:

1public static function where(
2 $array,
3 callable $callback
4);

#Example Use

In the following example, we will examine how to compare just the values of the arrays. Assume we have an array of numbers, from 0 to 100:

1$numbers = range(0, 100);

An array of all numbers less than or equal to 10 can be created like so:

1use Illuminate\Support\Arr;
2 
3$smallNumbers = Arr::where($numbers, function($key, $value)
4{
5 return ($value <= 10);
6});

$smallNumbers would then look like this:

1array {
2 [0] 0
3 [1] 1
4 [2] 2
5 [3] 3
6 [4] 4
7 [5] 5
8 [6] 6
9 [7] 7
10 [8] 8
11 [9] 9
12 [10] 10
13}

Now that we have looked at how to compare just the array values, let's examine ways to examine both the array key and value. That example only used the $value from the array, the following example will make use of both the key and value.

Consider the following array of students and test scores:

1$testScores = [
2 'Alice' => 95,
3 'Allison' => 96,
4 'Bob' => 92,
5 'Delbert' => 72,
6 'Dennis' => 87,
7 'Tonya' => 32
8];

Let's assume that any test score below a 70 is a failing grade. What we want to do is get an array of everyone who has passed the test, but whose name starts with the letter a:

1use Illuminate\Support\Arr;
2use Illuminate\Support\Str;
3 
4$studentsWhoPassed = Arr::where(
5 $testScores,
6 function($student, $testScore) {
7 return (Str::startsWith(Str::upper($student), 'A')
8 && $testScore >= 70);
9 });

The value of $studentsWhoPassed would be:

1array {
2 ["Alice"] 95
3 ["Allison"] 96
4}

For completeness, let's look at an example of just utilizing the key from the key/value compare with the where method.

Let's add another array to the mix to keep track of all the students that are currently suspended:

1$suspendedStudents = [
2 'Dennis',
3 'Tonya'
4];

Now we want to get only the test scores of those students who are not currently suspended (students who are suspended to not get their test scores credited, and instead receive a 0 mark):

1$validTestScores = Arr::where($testScores,
2 function($student, $testScore)
3 use ($suspendedPeople)
4{
5 return (!Arr::has(array_flip($suspendedPeople), $student));
6});
Anonymous Functions and Variable Scope

In PHP, whenever the execution of the script enters into a function, the scope changes. This is still true for Closures and anonymous functions. That is why the above example is using the use keyword: to bring the $suspendedPeople variable from another scope into the current scope.

It should be noted that when variables are "pulled into" the current scope, the current scope receives a copy of that variable. That is why the call to array_flip does not change the original array.

The value of $validTestScores would then be:

1array {
2 ["Alice"] 95
3 ["Allison"] 96
4 ["Bob"] 92
5 ["Delbert"] 72
6}

#Global array_where Helper Function

The array_where function is a shortcut to calling Arr::where. 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.