PHP array_filter() Tutorial 🎯

beginner
7 min

PHP array_filter() Tutorial 🎯

Welcome to this comprehensive guide on the PHP array_filter() function! In this lesson, we'll cover everything you need to know about array_filter(), from the basics to advanced use cases. By the end of this tutorial, you'll be able to filter arrays like a pro! πŸ’‘

What is array_filter()? πŸ“

In PHP, the array_filter() function is used to filter out elements from an array that pass a specified test. It's a handy tool for cleaning up data and ensuring your code works with only the necessary elements.

How to Use array_filter() πŸ’‘

The syntax for the array_filter() function is simple:

php
array array_filter(array $input, callable $callback, int $flags = 0): array

Here's a breakdown of the parameters:

  1. $input: The input array you want to filter.
  2. $callback: A callback function that tests each value in the input array. If the callback returns true, the value is kept in the filtered array; otherwise, it's removed.
  3. $flags (optional): A bitmask that determines how array_filter() behaves. We won't cover this parameter in this tutorial, but you can learn more about it in the PHP documentation.

Example 1: Removing Empty Values πŸ’‘

Let's start with a simple example. In this case, we'll use array_filter() to remove any empty values from an array:

php
$array = [1, "", 0, "abc", "", 3]; $filtered_array = array_filter($array); // Output: Array ( [0] => 1 [2] => 0 [3] => abc [5] => 3 )

In the example above, array_filter() removes the empty string values, leaving only the non-empty values in the filtered array.

Example 2: Custom Callback Function πŸ’‘

Now let's create a custom callback function to filter arrays based on specific criteria. In this example, we'll filter an array of user data to include only users who are at least 18 years old:

php
function isAdult($user) { return $user['age'] >= 18; } $users = [ ["name" => "John", "age" => 19], ["name" => "Sarah", "age" => 25], ["name" => "Mike", "age" => 17] ]; $adults = array_filter($users, 'isAdult'); // Output: Array ( [1] => Array ( ["name"] => "Sarah", ["age"] => 25 ) )

In this example, we defined a custom callback function isAdult(). This function checks whether the user's age is greater than or equal to 18, and if so, the user is included in the filtered array.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `array_filter()` function do in PHP?

That's it for this lesson! In the next tutorial, we'll cover more advanced uses of array_filter(), including using array_filter() with multiple callback functions and using it with associative arrays. Stay tuned! πŸ’‘