To filter items of a set based on a condition in PHP, you can iterate through the set and selectively add items that satisfy the condition to a new set.
In this example,
$numberSet
with values [1, 2, 3, 4, 5, 6]
.$evenNumbers
.$numberSet
using a foreach
loop.%
.$evenNumbers
set.<?php
$numberSet = [1, 2, 3, 4, 5, 6];
$evenNumbers = [];
foreach ($numberSet as $num) {
if ($num % 2 === 0) {
$evenNumbers[] = $num;
}
}
print_r($evenNumbers);
?>
[2, 4, 6]
In this example,
$stringSet
with values ["Apple", "Banana", "Apricot", "Orange"]
.$filteredStrings
.$stringSet
using a foreach
loop.strpos()
function.$filteredStrings
set.<?php
$stringSet = ["Apple", "Banana", "Apricot", "Orange"];
$filteredStrings = [];
foreach ($stringSet as $str) {
if (strpos($str, 'A') === 0) {
$filteredStrings[] = $str;
}
}
print_r($filteredStrings);
?>
["Apple", "Apricot"]
In this tutorial, we learned How to Filter Items of a Set based on a Condition in PHP language with well detailed examples.