PHP array_filter Function | Filter Array using Callback

PHP array_filter is an inbuilt function in PHP. It filters array elements using a callback function. It passes all elements of the array to a callback function. If the callback function returns false for a particular element, it deletes that element from the array. Also, it preserves the original keys of the array. In this article, we will discuss the PHP array_filter function. Also, we will discuss a few examples of using it.

PHP array_filter function

Syntax

array array_filter($array, $callbackFunction, $flag)

Parameters

The PHP array_filter Function expects three parameters. However, only one of them is mandatory and two are optional. The description of the parameters is as follows:

  • $array: The first parameter is the mandatory array which you need to filter.
  • $callbackFunction: The third parameter is the name of the callback function to filter elements. If no callback function is passed, the function removes all entries of the array equal to FALSE (null, empty, false etc).
  • $flag: The third parameter is the flag and it refers to the arguments to the callback function. By default, only the values are passed to the callback function. It can take two possible values.
    • ARRAY_FILTER_USE_KEY: It passes only the array keys to the function and not values.
    • ARRAY_FILTER_USE_BOTH: It passes both keys and values to the function.

Return Value

The PHP array_filter function returns the array after filtering.

Examples

Let’s discuss a few examples of using the PHP array_filter function.

Example 1: Filtering Out Odd Elements

For example, suppose we want to filter out odd elements from our array. We can use the PHP array_filter function along with a custom callback function as follows:

<?php

	function filter_odd($element) {
		if ($element % 2 == 0) {
			return true;
		}
		return false;
	}

	$testArray = array(1, 2, 3, 4, 5, 6);
	$filteredArray = array_filter($testArray, 'filter_odd');
?>

The callback function returns true if the element is even, and returns false otherwise. The final array looks like this:

OUTPUT:
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
)
//The final array has the original keys of the array preserved.

Example 2: Using PHP array_filter without Callback Function

Now, let us observe what happens when we don’t pass any callback function.

<?php

	$testArray = array('foo', false, -1, null, '');
	$filteredArray = array_filter($testArray);
?>

When we don’t pass any callback function to the array_filter function, it removes all the elements equal to FALSE. In the above example, the function will remove false, null and empty string.

OUTPUT:
Array
(
    [0] => foo
    [2] => -1
)

Example 4: Using ARRAY_FILTER_USE_KEY Flag

For instance, let’s consider situation where we want to filter out an array on the basis of keys. We can pass the ARRAY_FILTER_USE_KEY flag to the callback function to pass array keys instead of values to the callback function.

<?php

	function filter_keys($key) { 
		if ($key == 'a' || $key == 'c') {
			return true;
		} else {
			return false;
		}
	}

	$testArray = array('a' => 'apple', 'b' => 'ball', 'c' => 'cat', 'd' => 'dog');
	$filteredArray = array_filter($testArray, 'filter_keys', ARRAY_FILTER_USE_KEY);
	print_r($filteredArray);
?>

In the above example, the callback function returns true when the key is equal to ‘a’ or ‘c’ and false otherwise. The output of the PHP array_filter function is as follows:

Array
(
    [a] => apple
    [c] => cat
)

Example 4: Using ARRAY_FILTER_USE_BOTH Flag

Similarly, we can pass the ARRAY_FILTER_USE_BOTH flag to the function to send both keys and values to the callback function. In such scenario, the callback function also has two parameters.

<?php	
        $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
	$filteredArray = array_filter($arr, function($v, $k) {
    	      return $k == 'b' || $v == 4;
	}, ARRAY_FILTER_USE_BOTH);
	print_r($filteredArray);
?>

In the above example, we pass both the array keys and values of the Associative Array. Also, we use a lambda callback function. We will discuss about Lambda or Anonymous Functions later. The final array is as follows:

Array
(
    [b] => 2
    [d] => 4
)

Expert Advice

If you want to remove false, null and empty strings but want to retain zero (0) values, you can use the inbuilt PHP strlen Function.

<?php

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

?>

Conclusion

In conclusion, we discussed the PHP array_filter Function. You can read more about it on the Official PHP Documentation. Additionally, you can learn more about PHP Arrray Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *