I have an array("https", "www", "stackoverflow", "com")
$search_array = array("https", "www", "stackoverflow", "com");
for ($i=0; $i < count($search_array); $i++) {
if (
$search_array[$i] == null ||
strtolower($search_array[$i]) == "http" && count($search_array) > 1 ||
strtolower($search_array[$i]) == "https" && count($search_array) > 1 ||
strtolower($search_array[$i]) == "www" && count($search_array) > 1 ||
strtolower($search_array[$i]) == "com" && count($search_array) > 1
) unset($search_array[$i]);
}
die(print_r($search_array));
I want the result array("stackoverflow");
, but im getting the result array("stackoverflow", "com");
any idea?
5
Answers
You are modifying the array while looping around it. This causes the for loop to not run for all of the elements inside it. You can verify this by calling
echo $i
where you currently dounset()
.Also your if statements need brackets around them to ensure that the
&&
and||
run in the correct order.To get the result you want, create a new array of the valid values that you want to save:
You’re changing the value of your loop exit condition inside your loop – which is usually a bad idea.
On unsetting the array value, the array length gets lower, and thus the last iteration is never run.
first run (after unset):
$i=0; $search_array = array("www", "stackoverflow", "com"); count($search_array)=3
second run (after unset):
$i=1; $search_array = array("stackoverflow", "com"); count($search_array)=2
now your loop won’t run again, as next $i would be 2, and this is now triggering your exit condition…
As pointed out in the comments and other answers, you have an issue when looping and
unset()
-ing. The answers show how to handle this when using afor()
loop, but you can also simply use aforeach()
:Output from this approach is:
In addition to what others here correctly point out and demonstrate I would like to suggest to take a somewhat more direct approach: always use the right tool for your task.
What you are trying to do is filter the input array, right? Then why don’t you use the
array_filter()
function which does exactly that?The output obviously is:
Think I might be late, but this is happening because you were modifying the original array. A much more cleaner way of doing this would be as follows: