Filtering with array functions [part 3]
Coding (Php 7.x)
Following the examples, on this tutorial, you will learn how to filter elements with array functions
Introduction to part 3: Filter arrays
This is the third chapter of the series in which we will break down an entire other section on array functions.
This part is all about filtering elements from an array.
There are dozens and dozens of cases in which our scripts only need certain elements present in an array, while other elements, besides being useless for our purpose, make our applications slower and our code more confusing.
PHP offers several functions that allow you to filter only the elements we want to work on, making our code easier to read and work on.
If you want to step back from arrays' function for a while and maybe learn some new tricks and fixes of PHP head over the series about the basics of PHP.
About the series
This blog post that belongs to the series "PHP array exposed".
If you haven't already read the other articles
have a look at them:
PHP array Exposed (part one)
Creation and Manipulation of Arrays
Filtering Arrays elements
Sorting Elements of array
Table of content
- array_filter()
- array_reduce()
- array_intersec()
- array_intersect_assoc()
- array_diff_assoc()
- max()
- min()
- count() & sizeof()
- Conclusion
array_filter()
As mentioned this is the section of the series that concerns the filtering of elements within an array, so let's start with a classic:
array_filter()
This function requires a mandatory parameter which is the array on which we want to apply the filter and two other unnecessary parameters.
The first is preferable to insert it anyway, it consists of a callback function, the second of the non-mandatory parameters consists of flags that determine the use of keys or the key-value pair.
Let's go to the point, how does array_filter() work?
This function cycles all the elements of the array as the first parm and passes them to the array function used as a callback, one after the other.
If, after evaluating the element, the function returns true the value is returned inside the array if not filtered out.
Note that the array keys are preserved.
If you have already seen some episodes of this series, you will already know that I use simple references to understand.
In this case, instead, I will shamelessly steal an example from the PHP.net manual,
The reason is simple, I believe that the proposed example is quite difficult for a beginner and I am taking this opportunity to explain it, in simple words.
Here is the example proposed:
function odd($var) { // returns whether the input integer is odd return($var & 1); } function even($var) { // returns whether the input integer is even return(!($var & 1)); } $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); $array2 = array(6, 7, 8, 9, 10, 11, 12); echo "Odd :\n"; print_r(array_filter($array1, "odd")); echo "Even:\n"; print_r(array_filter($array2, "even")); Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 )
In the example above the function array_filter() takes an array as a parameter and invokes a function (second parameter), the function, in turn, evaluates the element passed as an attribute and returns a Boolean value.
Now, what is this?
return($var & 1);
It's a AND operation in BITWISE.
All even numbers have the least significant bit set to 0, whereas all odd numbers have the least significant bit set to 1.
So it simply "ANDs" two numbers together.
3 for instance, it is represented as 11 in binary. 11 & 01 = 01 => true, so it is odd.
2 instead, it is represented as 10 in binary. 10 & 01 = 00 => false, so it is even.
I have already described the BITWISE operators during an article on the basics of PHP.
It will surely increase your skills.
click here to learn more about Bitwise
array_reduce()
There is a lot of confusion and wrong information online about this array function.
Which makes it one of the least used features I've ever seen in my career.
array_reduce() needs a callback function which makes it more complicated than average, the more difficult part is that the callback requires two parameters to work.
Let's take a look,
What this function does is to Iteratively reduce the array to a single value using a callback function.
What does it mean?
In simple terms, this function takes an array and, after processing the elements according to a callback, returns a single variable from it.
As you can imagine this function takes at least 2 parameters, the first is the array to be processed, the second is the function callback that does the job.
A third parameter concerns the initial value from which we want to start in our callback, however, it is not mandatory to use it.
function addComma($e1,$e2) { return $e1 . ", " . $e2; } $dwarfs = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'); print_r(array_reduce($dwarfs,"addComma")); // Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy print_r(array_reduce($dwarfs,"addComma", "Dwarfs")); // Dwarfs, Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy
If you want to learn more about this function, here is an article by Gordon Forsythe: Reaching that goes deep into arrays using array_reduce in PHP
array_intersec()
We have gone from a fairly complicated function to understand to a very simple one.
array_intersec() is in fact very simple, being one of the first available functions since it was first published in PHP 4.0.1.
Its task is to filter the elements of an array, indicated as the first mandatory parameter and commonly called a master array, against one or more selected arrays as subsequent parameters.
If an element is present in the master array and is also present in any of the others then it will be returned to the resulting array.
$dwarfs1 = array('Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'); $dwarfs2 = array('Doc', 'Dopey'); $dwarfs3 = array('Doc', 'Grumpy', 'Dopey', 'Bashful', 'Sneezy'); $result=array_intersect($dwarfs1, $dwarfs2, $dwarfs3); print_r($result); Array ( [0] => 'Doc', [1] => 'Dopey' )
Note that, to be treated as equal elements, the value of the comparison === between them must be in true.
array_intersect_assoc()
This function came shortly after the previous one, and like the previous one, it inherits a very simple syntax to understand.
array_intersect_assoc() takes a minimum of 2 arrays as parameters, filters the first array, called master, with the others.
if both keys and values are identical in all the arrays provided, then they will be added to the array returned by the function.
$dwarfs = array( 'first' => 'Grumpy', 'second' => 'Happy', 'third' => 'Sleepy', 'fourth' => 'Dopey', 'fifth' => 'Bashful', 'sixth' => 'Sneezy', 'seventh' => 'Doc' ); $dwarfs2 = array( 'first' => 'Grumpy', 0 => 'Happy', 1 => 'Dopey', 2 => 'Bashful', 'sixth' => 'Sneezy', ); $dwarfs3 = array( 'first' => 'Grumpy', 0 => 'Dopey', 'sixth' => 'Sneezy', ); $result=array_intersect_assoc($dwarfs1, $dwarfs2, $dwarfs3); print_r($result); Array ( ['first' ] => 'Grumpy', ['sixth'] => 'Sneezy')
As you can see the filtering returned only 2 of all elements within the arrays.
In all three arrays there is the pair ['first'] => 'Grumpy' and ['sixth'] => 'Sneezy'.
You can also note that in all arrays there is the value ‘Dopey’, but it has different keys so it is not evaluated.
array_diff_assoc()
Another relative of the functions explained above and another function that is part of the 'array filters' category.
array_uintersect() works in a way very similar to array_intersect() but differs in the fact that it has a callback function, indicated as the last parameter, that compares arrays' elements provided.
function comparison($a,$b) { return $a ⇔ $b; } $dwarfs1 = array('Doc', 'Grumpy', 'Sneezy'); $dwarfs2 = array('Doc', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'); print_r(array_uintersect($dwarfs1, $dwarfs2, "comparison")); Array ( [0] => 'Doc', [1] => 'Sneezy')
Note that from PHP 5 the language provides the function array_intersect_assoc(), it works similarly to array_intersect() but it compares both keys and values.
The family of array_intersect and array_diff is quite big, counting 10 elements in total, they are all very similar both in working methods and syntax so here is the list and a few little hints if you decide to dive into them:
- array_intersect,
- array_ intersect_ assoc,
- array_ intersect_ key,
- array_ intersect_ uassoc,
- array_ intersect_ ukey,
- array_ diff
- array_ diff_ assoc,
- array_ diff_ key,
- array_ diff_ uassoc,
- array_ diff_ ukey,
Legend:
Intersect: Computes the intersections;
Diff: Computes the difference;
Assoc: evaluates both keys and values;
Uassoc: the callback function is used for the indices comparison;
Ukey: evaluates the keys;
max()
It will surely happen that during your career, you will have to at least once look for the maximum value between a series of variables or between the elements within an array,
PHP 4 has provided you with its own programmers a feature to make this search much easier.
the max() function takes an array as a parameter or two or more variables that can be of different types and compare each of them returning the maximum value.
You can also evaluate different types of variables and they will be evaluated using standard comparison rules.
$maxNumber = max(2, 3, 1, 6, 7); // 7 $maxArrayElement = max([2, 4, 5]); // 5 $maxDwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; // 'Doc' // The string 'hello' when compared to an int is treated as 0 $maxIntString = max(1, 'Doc'); // 1 // Multiple arrays compares the elements from left to right 3 < 4 $maxArray = max([1, 2, 3], [1, 2, 4]); // [1, 2, 4] // The value 0 is evaluated as false whereas TRUE is evaluates as 1 $maxIntBool = max(0, TRUE); // TRUE
min()
the min() function finds the smallest value among a set of values.
basically, if you invert all that is written in the part regarding the max() function you will get the result of min().
count() & sizeof()
If you are working with an element that is an array or an object that implements the built-in interface of PHP Countable, you can use the array count() function.
This function works for both arrays and objects.
If you want to learn more about object-oriented programming, read the series dedicated to OOP in PHP
count() takes 2 values as a parameter, the first and the variable to be counted, the second parameter, which is not mandatory, consists of a flag that defines the counting method.
The flag can have two values: COUNT_NORMAL and COUNT_RECURSIVE, the second is useful in the case of associative arrays.
$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; var_dump(count($dwarfs)); // int(7) $disney = [ "dwarfs" => ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'], "originals" =>["Mickey Mouse","Pete", "Goofy", "Minnie Mouse", "Pluto"] ]; // Normal count var_dump(count($disney)); // int(2) // Recursive count var_dump(count($disney, COUNT_RECURSIVE)); // int(14)
Some more about the count function on the official manual
Conclusion
As you have seen, the portfolio of array functions that PHP has provided us with, and continues to give us, is incredibly broad,
In this section of the series we have seen extremely simple functions, for example, the pair min() and max(), and others that go deeper in detail like array_ intersect_ uassoc().
The good news is that there is no job and no open vacancy that requires you to know all these functions by heart,
Another good news is that, now that you understand them, you can mark this post on your browser and return whenever you want.
After discussing the filters, in the next chapter of the series, you will go to see another part that constitutes the foundation of PHP functions.
How to order items inside.
If you have learned something new today and have not already done so, subscribe to the newsletter in order to be notified when the next chapter is published.
If you like this content and the next set of examples on arrays functions, stay tuned and subscribe to the newsletter so you will be notified.
If you want to learn more about PHP array functions take a look at the tutorials already published which are part of this series by clicking on the links below.
PHP array Exposed (part one)
Creation and Manipulation of Arrays
Filtering Arrays elements
Sorting Elements of array
***
Learn to code, gain a new skill, get a new job
Whatever your goal — Treehouse will get you there
They are currently making a free 4-month offer (valued at $ 100).