Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Filtering With Array Functions (Part 3)

DZone 's Guide to

Filtering With Array Functions (Part 3)

In this tutorial, we will learn how to filter elements with array functions.

· Web Dev Zone ·
Free Resource
/img/blog/filtering-with-array-functions.jpg

Introduction to Part 3: Filter Arrays 

This is the third part of this series in which we break down an entire other section on array functions. You can find the first two parts here: 

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 purposes, make our applications slower and our code more confusing. 

PHP offers several functions that allow you to filter only the elements you want to work on, making your code easier to read and work on.

About the Series

This blog post belongs to the series "PHP Arrays Exposed."

Table of contents:

  • array_filter() 
  • array_reduce()
  • array_intersec()
  • array_intersect_assoc()
  • array_diff_assoc()
  • max()
  • min()
  • count() and sizeof()
  • Conclusion

array_filter() 

As mentioned above, 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 it's not filtered out. 

Note that the array keys are preserved.

If you have already read the other articles in 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 an 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 iteratively reduce the array to a single value using a callback function.

What does this 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 two 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 two arrays as parameters, and 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 two 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' provided elements.

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 on, 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 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() and 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 count() function.

count() takes two values as a parameter: the first is 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));
// int(14)

Some more about the count function in the official PHP 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.

More 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 post of the series, we will look at another part that constitutes the foundation of PHP functions: how to order items inside arrays.

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.

Topics:
web dev ,php arrays ,php tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}