PHP array_filter() Function

Learn via video courses
Topics Covered

Overview

PHP provides programmers with a wide range of array manipulation methods. One of them is the array_filter() method, which allows us to filter and remove elements from an array effectively depending on predefined criteria. The array_filter() method, including its syntax, argument values, return value, and examples of real-world applications, will be thoroughly explained in this article.

Introduction to PHP array_filter() Function

The array_filter() function in PHP is used to iterate over an array and selectively filter its elements based on a callback function. A callback function is a function that is passed as an argument to another function. The purpose of a callback function is to allow the receiving function to execute the callback at a specific point in its execution or in response to a certain event.

The array_filter() method generates a new array that includes only the elements that satisfy the callback function's evaluation. This function proves beneficial when there is a requirement to extract specific values from an array or eliminate undesired elements.

Syntax of PHP array_filter() Function

The syntax of the array_filter() function is as follows:

Parameter Values of PHP array_filter() Function

  • $array (required): This is the input array that will be filtered.
  • $callback_function (optional): This is the callable function that defines the condition for filtering. It can be either a named function, an anonymous function, or a method of an object.
  • $flag (optional): This is an integer value that specifies additional behavior for the function. The available flags are:
    • ARRAY_FILTER_USE_KEY: This callback function receives the keys of the array as the argument.
    • ARRAY_FILTER_USE_BOTH: This callback function receives both the key and value of the array as arguments.

Return Value of PHP array_filter() Function

The array_filter() method in PHP creates a new array that contains just the elements for which the callback function returns true. Unless the ARRAY_FILTER_USE_KEY option is set, the method keeps the array's original keys.

PHP Version

The PHP language has supported the array_filter() method starting from version 4.0.6, and this functionality continues to be available in all subsequent PHP versions, including the current ones.

PHP Changelog

In PHP 5.6, the array_filter() function underwent optimization to enhance its performance with large arrays. Additionally, it also added the optional flag parameter. Since then, no significant modifications have been introduced to this function.

Example Program for Using array_filter() Function

Let's look at some examples of using the array_filter() function:

Example 1

Output

Explanation

In this example, an array named $names is initialized with four names: 'Virat', 'Shubman', 'Rishabh', and 'Rohit'. The objective is to filter this array based on a condition.

To accomplish this, the array_filter() function is utilized with an anonymous function as the callback. This function evaluates each element of the $names array, checking if the length of a name exceeds 5 characters and returning true or false accordingly. By applying array_filter() to $names using the anonymous function, a new array called $filteredNames is created. It contains only the elements from $names that meet the condition, preserving the original keys.

Finally, the contents of $filteredNames are displayed using print_r(). The output indicates that two names, 'Shubman' and 'Rishabh', satisfy the condition and have been included in the filtered array, along with their respective keys.

Example 2

Output

Explanation

In this example, an array named $numbers is defined with the values [1, 2, 3, 4, 5]. The array_filter() function is then used on $numbers, accompanied by an anonymous function as the callback. This callback function takes each element of the array as an argument and checks if it is an odd number. If the condition evaluates to true, the element is included in the resulting array.

The output of the code is displayed using the print_r() function, which reveals the resulting array containing only the odd numbers: [1, 3, 5]. The filtered array preserves the original keys associated with each number.

Example 3

Output

Explanation

In this example, the array_filter() function is used with an anonymous function as the callback. An additional flag, ARRAY_FILTER_USE_KEY, is specified as the third parameter of array_filter(). This flag instructs array_filter() to use the keys of the array when applying the callback function. By doing so, the callback function is applied to the keys (player names) rather than the values of the array.

The callback function receives the key (player name) as input and checks if the length of the key exceeds 5 characters. If the condition is met, it returns true. Otherwise, it returns false.

Common Use Cases and Best Practices for array_filter()

  • Filtering based on a condition: We can use the array_filter() method to extract elements from an array that meet specific conditions defined by the callback function.
  • Removing empty or falsy values: We can utilize array_filter() to eliminate empty or falsy values from an array, resulting in a cleaner dataset.
  • Modifying array values: The array_filter() can be used to transform or manipulate values of the filtered elements within the callback function.
  • Preserving array keys: The array_filter() method retains the original keys of the filtered elements, maintaining key-value associations.
  • Performance considerations: We should be mindful of performance when working with large arrays and keep the callback function efficient to optimize the filtering process.

Conclusion

  • The array_filter() method in PHP is a very handy tool for filtering and retrieving array components depending on certain criteria.
  • Developers may efficiently use arrays in their PHP applications by understanding the function's syntax and parameter values.
  • The array_filter() function has been around since PHP 4.0.6 and has been optimized for better performance with huge arrays in PHP 5.6.
  • Developers can implement customized filtering criteria to meet their individual needs by utilizing callback functions.
  • The function returns a new array containing just the elements that were evaluated by the callback function.
  • When working with arrays in PHP, understanding and mastering array_filter() can lead to simpler and more maintainable code.