PHP

Filter an Array Based on a Callback Function

Learn to efficiently filter PHP arrays, keeping only elements that satisfy a specific condition using array_filter and a custom callback function.

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$evenNumbers = array_filter($numbers, function($number) {
    return $number % 2 === 0;
});

print_r($evenNumbers);
// Output: Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
How it works: This snippet demonstrates how to use `array_filter` to create a new array containing only elements that pass a certain condition. The callback function is executed for each element, and if it returns `true`, the element is included in the resulting array. This is highly useful for data cleaning or selection.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs