PHP: unset from array using if statement
There are many ways to Rome, as they say..
Using foreach()
A cleaner approach would be to use foreach
instead of for
loops, and checking against an array using in_array()
instead of individually checking all the fruits.
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
foreach ($fruits as $key=>$fruit) {
if (in_array($fruit, ['apple', 'orange', 'melon', 'banana'])) {
unset($fruits[$key]);
}
}
print_r($fruits);
Using array_filter()
A more "fancy" way would be a one-liner using array_filter()
,
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
$fruits = array_filter($fruits, function($fruit) {
return !in_array($fruit, ['apple', 'orange', 'melon', 'banana']);
});
print_r($fruits);
Using array_diff()
Even simpler, use array_diff()
, which finds all elements that exists in only one of the arrays (essentially removing the duplicates).
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
$remove = ['apple', 'orange', 'melon', 'banana'];
$result = array_diff($fruits, $remove);
Using array_intersect()
There's also array_intersect
, which is sort of the inverse of array_diff()
. This would find elements that exists in both arrays, and return that.
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
$find = ['pineapple'];
$result = array_intersect($fruits, $find);
- Live demo using
foreach()
- Live demo using
array_filter()
- Live demo using
array_diff()
- Live demo using
array_intersect()
- PHP.net on
in_array()
- PHP.net on
array_diff()
- PHP.net on
array_filter()
- PHP.net on
array_intersect()
- PHP.net on
foreach()
Because after removing the first 3 element the $i
value is 3 but the count of the array is 2 so the for loop breaks - remember the loop condition is re-evaluating in each iteration. Change to this will give you the desire output:
$size = count($fruits)
for ($i = 0 ; $i < $size; $i++){
Generally, using unset
with for
loop with int index is not recommended
I think problem is $i<count($fruits)
. It reduce the array size. So it's runs only 3 times. SO assign the array size to variable first.
<?php
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
$n=count($fruits);
for ($i = 0 ; $i <$n ; $i++){
if ($fruits[$i] == 'apple' || $fruits[$i] == 'orange' || $fruits[$i] == 'melon' || $fruits[$i] == 'banana'){
unset($fruits[$i]);
}
}
print_r($fruits);
?>