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! π‘
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.
The syntax for the array_filter() function is simple:
array array_filter(array $input, callable $callback, int $flags = 0): arrayHere's a breakdown of the parameters:
$input: The input array you want to filter.$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.$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.Let's start with a simple example. In this case, we'll use array_filter() to remove any empty values from an array:
$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.
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:
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.
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! π‘