I want to loop through an array and check if some elements is equal to a specific condition .
For example , I want to remove the element contains "O"
, so I can do in this way ..
@Array = ("Apple","Orange","Banana");
for ($i=0 ; $i <= $#Array ; $i++) {
if( index($Array[$i],"O") >= 0 ) {
splice(@Array,$i,1);
}
}
but if I want to use foreach
loop to replace for
loop , how do I do ? because in foreach
loop , there is no index so I can't use splice
, unless I set a variable to store it .
Use unset () function to remove array elements in a foreach loop. The unset () function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things.
It is safe in PHP to remove elements from an array while iterating over it using foreach loop: Show activity on this post. Use key () to get the first key from the sub-array.
Since the for-each loop hides the iterator, you cannot call the remove() directly. So in order to remove items from a for-each loop while iterating through it, have to maintain a separate list. That list will maintain references to the items to be removed...
BTW, you can still use a foreach -style for loop to process and remove elements — without having to build a whole new array... Show activity on this post. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid …
If you want to remove elements, the better tool is grep
:
@array = grep { !/O/ } @array;
Technically, it is possible to do with a for
loop, but you'd have to jump through some hoops to do it, or copy to another array:
my @result;
for (@array) {
if (/O/) {
push @result, $_;
}
}
You should know that for
and foreach
are aliases, and they do exactly the same thing. It is the C-style syntax that you are thinking of:
for (@array) { print $_, "\n"; } # perl style, with elements
for (my $x = 0; $x <= $#array; $x++) { # C-style, with indexes
print $array[$x], "\n";
}
BTW, you can still use a foreach
-style for
loop to process and remove elements — without having to build a whole new array...
Just work backwards from beginning-to-end:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
my @fruits = qw< Apple Orange Banana >;
for my $index ( reverse 0 .. $#fruits ) {
my $item = $fruits[$index];
if ( $item =~ /^O/ ) {
# Do something...
say "Removing #$index: $item";
# Remove the current item...
splice @fruits => $index, 1;
}
}
Or, in the spirit of TMTOWTDI:
say "Removing #$_: " . splice @fruits => $_, 1
for grep $fruits[$_] =~ /^O/, reverse 0 .. $#fruits;
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