Filtering with array functions [part 3]
Tags: php, arrays, phptutorial, phparrayfunctions
Published: 2019-04-09 08:34:08

---
title: Filtering with array functions [part 3]
published: true
description: Following the examples, on this tutorial, you will learn how to filter elements with array functions
tags: php, arrays, php tutorial, php array functions
series: PHP arrays exposed
cover_image: https://thepracticaldev.s3.amazonaws.com/i/j4gip4yvqdcplmd1q8a7.jpg
---



Following the examples, on this tutorial, you will learn how to filter elements with array functions 
 
 
   
 
 
 

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.  
 &nbsp;

 
## About the series
 

This&nbsp;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)](http://anastasionico.uk/blog/php-array-functions-exposed)  
 [Creation and Manipulation of Arrays](http://anastasionico.uk/blog/array-function-in-php)

 

Table of content
[array_filter() ](http://anastasionico.uk/blog/filtering-with-array-functions#filter)
[array_reduce()](http://anastasionico.uk/blog/filtering-with-array-functions#reduce)
[array_intersec()](http://anastasionico.uk/blog/filtering-with-array-functions#intersec)
[array_intersect_assoc()](http://anastasionico.uk/blog/filtering-with-array-functions#interassoc)
[array_diff_assoc()](http://anastasionico.uk/blog/filtering-with-array-functions#diffassoc)
[max()](http://anastasionico.uk/blog/filtering-with-array-functions#max)
[min()](http://anastasionico.uk/blog/filtering-with-array-functions#min)
[count() & sizeof()](http://anastasionico.uk/blog/filtering-with-array-functions#count)
[Conclusion](http://anastasionico.uk/blog/filtering-with-array-functions#conclusion)
 
## array\_filter()&nbsp;
 

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.&nbsp;

 

Here is the example proposed:  
 &nbsp;

 
```php
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?&nbsp;

 

return($var & 1);

 

It's a AND operation in BITWISE.&nbsp;

 

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](http://anastasionico.uk/blog/php-operators#bitwise)

 
## &nbsp;
 
## &nbsp;
 
## 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.

 
```php
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](https://medium.com/@baohx2000/reaching-deep-into-arrays-using-array-reduce-in-php-9ff9e39a9ca8) in&nbsp;PHP

 
## &nbsp;
 
## 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.

 
```php
$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.

 
```php
$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**.  
 &nbsp;

 
```php
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;  
 &nbsp;

 
## &nbsp;
 
## 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.

 
```php
$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()_**.

 
## &nbsp;
 
##   
 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.

 

_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.

 
```php
$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 on the official manual](https://www.php.net/manual/en/function.count.php)

 
## &nbsp;
 
## 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**.  
 &nbsp;

 

\*\*\*

 

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)](http://anastasionico.uk/blog/php-array-functions-exposed)  
 [Creation and Manipulation of Arrays](http://anastasionico.uk/blog/array-function-in-php)

 

\*\*\*


  
 
  [![get the weekly book's review](https://cdn-images-1.medium.com/max/800/1*8FKpkkhRhWP0iLk7FpzTbQ.jpeg) ](https://anastasionico.us12.list-manage.com/subscribe?u=58fde30bf74e04ab41c7afea8&id=13c59ad6f4)
 
  

\*\*\*



 

[![](http://anastasionico.uk/img/1/3944-517995.png)](http://treehouse.7eer.net/c/1374240/294479/3944)

 
### 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).](http://treehouse.7eer.net/c/1374240/294479/3944)

 

[Have a look at it!.](http://treehouse.7eer.net/c/1374240/294479/3944)

 

([Affiliate links](http://treehouse.7eer.net/c/1374240/294479/3944))