To filter elements of an array based on a condition in PHP, you can use the array_filter function.
In this example,
numbers
containing integers.filterEven
to filter out even numbers.array_filter
with our custom callback to get the filtered array.<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function filterEven($num) {
return $num % 2 === 0;
}
$evenNumbers = array_filter($numbers, 'filterEven');
print_r($evenNumbers);
?>
Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
In this example,
words
containing strings.filterByLength
to filter strings by their length.array_filter
with our custom callback to get the filtered array.<?php
$words = ['apple', 'banana', 'cherry', 'date', 'fig'];
function filterByLength($word) {
return strlen($word) > 5;
}
$filteredWords = array_filter($words, 'filterByLength');
print_r($filteredWords);
?>
Array ( [1] => banana [2] => cherry )
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in PHP language with well detailed examples.