To remove items from a set (which can be represented using an array) based on a condition in PHP, you can use the array_filter
function.
In this example,
$numberArray
with values $numberArray = [1, 2, 3, 4, 5];
.array_filter
function to filter out the even numbers from the array. This function takes the array and a callback function as arguments.%
. If the number is odd, the callback function returns true
, and the number is kept in the array.$filteredArray
.<?php
$numberArray = [1, 2, 3, 4, 5];
echo "Original Array: ";
print_r($numberArray);
$filteredArray = array_filter($numberArray, function($number) {
return $number % 2 !== 0;
});
echo "Array after removing even numbers: ";
print_r($filteredArray);
?>
Original Array: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array after removing even numbers: Array ( [0] => 1 [2] => 3 [4] => 5 )
In this example,
$stringArray
with values $stringArray = ["apple", "banana", "orange", "kiwi"];
.array_filter
function to filter out the strings longer than 4 characters from the array. This function takes the array and a callback function as arguments.strlen
function. If the condition is true, the callback function returns true
, and the string is kept in the array.$filteredArray
.<?php
$stringArray = ["apple", "banana", "orange", "kiwi"];
echo "Original Array: ";
print_r($stringArray);
$filteredArray = array_filter($stringArray, function($str) {
return strlen($str) <= 4;
});
echo "Array after removing strings longer than 4 characters: ";
print_r($filteredArray);
?>
Original Array: Array ( [0] => apple [1] => banana [2] => orange [3] => kiwi ) Array after removing strings longer than 4 characters: Array ( [3] => kiwi )
In this tutorial, we learned How to Remove Items from Set based on a Condition in PHP language with well detailed examples.