I'm trying to unset specific values using if statement. My code is
$fruits = ['apple', 'orange', 'melon', 'banana', 'pineapple'];
for ($i = 0 ; $i < count($fruits); $i++){
if ($fruits[$i] == 'apple' || $fruits[$i] == 'orange' || $fruits[$i] == 'melon' || $fruits[$i] == 'banana'){
unset($fruits[$i]);
}
}
print_r($fruits);
I'm expecting it to return
Array
(
[4] => pineapple
)
But the result is
Array
(
[3] => banana
[4] => pineapple
)
Why isn't 'banana' unset from the array?
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.
You have to use for loop for this. you can use foreach loop but it will not unset all variable one variable still remains.
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.
There are many ways to Rome, as they say..
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);
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);
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);
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);
foreach()
array_filter()
array_diff()
array_intersect()
in_array()
array_diff()
array_filter()
array_intersect()
foreach()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With