To remove an element from an array in PHP based on a condition, you can use a combination of array functions such as array_filter
and array_values
.
In this example,
$numbers
with integer elements.array_filter
function with a custom callback function to filter out even numbers from the array.array_values
function to reindex the array after filtering.<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$filtered = array_filter($numbers, function($value) {
return $value % 2 !== 0;
});
$result = array_values($filtered);
print_r($result);
?>
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 )
In this example,
$fruits
with string elements.array_filter
function with a custom callback function to remove elements with a specific value from the array.array_values
function to reindex the array after filtering.<?php
$fruits = array("apple", "banana", "cherry", "banana", "date");
$filtered = array_filter($fruits, function($value) {
return $value !== "banana";
});
$result = array_values($filtered);
print_r($result);
?>
Array ( [0] => apple [1] => cherry [2] => date )
In this tutorial, we learned How to Remove Element from Array based on a Condition in PHP language with well detailed examples.