Get your next remote job on LaraJobs.
1 contributor Edit on GitHub PHP

Understanding array_filter() in PHP

Table of contents:

Understanding array_filter() in PHP

Introduction to array_filter()

array_filter() is a powerful function in PHP. It allows you to filter elements of an array using a callable (a closure for instance). Let me guide you in using this super handy function.

Basic usage of array_filter()

array_filter() works by passing each element of an array through a callback function. If this function returns true, the element is included in the resulting array. This is particularly useful when you need to sift through data and only keep elements that meet certain conditions.

Here’s a simple example:

$array = [1, 2, 3, 4, 5];
 
$even = array_filter($array, fn ($value) => $value % 2 == 0);
 
print_r($even);

In this snippet, array_filter() retains only the even numbers from the original array.

Advanced usage of array_filter()

Beyond simple filters, array_filter() can be used in more complex scenarios. For instance, you can filter an array of objects based on the properties of those objects. It’s also possible to use it with associative arrays, filtering by key as well as value.

Common pitfalls when using array_filter()

When using array_filter(), remember that the callback function must return true or false.

$array = [1, 2, 3, 4, 5];
 
$even = array_filter($array, function ($value) {
$value % 2 == 0;
});
 
// []
print_r($even);

If you don’t, the resulting array will be empty.

To finish this up, another common mistake is forgetting that array keys are preserved. This might lead to unexpected gaps in the numeric array indexes:

$array = [1, 2, 3, 4, 5];
 
$even = array_filter($array, fn ($value) => $value % 2 == 0);
 
// Array
// (
// [1] => 2
// [3] => 4
// )
print_r($even);
Benjamin Crozat

Written by Benjamin Crozat

Indie hacker, blogger, and AI enthusiast building things with the TALL stack. 🔥

Follow me on:

Recommended articles

Print an array with PHP (+ Laravel) Print an array with PHP (+ Laravel)

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP (and even Laravel-specific helpers).

Modified on Jun 24, 2023

The fastest way to check if your PHP array is empty The fastest way to check if your PHP array is empty

There are multiple ways to check if an array is empty. Let me tell you about each of them and why and when you should use them.

Modified on Nov 2, 2023 Audio available

PHP
Easily convert a PHP array to JSON Easily convert a PHP array to JSON

Convert PHP arrays to JSON with `json_encode()`. Ideal for data exchange, storing data, and API communication.

Published on Sep 16, 2023

PHP
14 Laravel Collections tips to refactor your codebase 14 Laravel Collections tips to refactor your codebase

Laravel Collections make arrays more powerful and convenient to work with. This article provides tons of quick tips to instantly make your codebase better.

Modified on Aug 27, 2023

Learn how to sort any kind of array in PHP Learn how to sort any kind of array in PHP

Let me walk you through some of the most useful functions in PHP that will enable you to sort any kind of array.

Published on Nov 9, 2023

PHP
Bring order back to your PHP arrays using array_values() Bring order back to your PHP arrays using array_values()

Discover how array_values() in PHP can help you re-do what has been undone.

Published on Nov 11, 2023

PHP

Gold sponsors New

  • Wire Elements
    Beautiful handcrafted Livewire components.
    Check site
Your business here

Partners

If you buy from one of my partners below, I will be compensated at no cost to you. These are services I use or used, and 100% stand behind.

  • Scalable and reliable VPS hosting.
    Bonus: $200 of free credits
    Check site
  • The Google Analytics alternative without compromise.
    Free trial: 30 days
    Bonus: $10 off your first invoice
    Check site
  • Flare
    Track PHP and JavaScript errors in one place.
    Free trial: 10 days
    Check site
  • Keep track of your Google rankings.
    Free trial: 7 days
    Promo code: WELCOME30
    Check site
- / -