0

I have an array constructed out of several strings (HTTP addresses) on which I run a PHP Filter and the unset() method to remove non-valid URLs. However, the last array item is never removed - and I don't know why, or how I solve this. I'm hoping you guys can help.

$url1 = "http://localhost/work/project/scrapes/1.html";
$url2 = "";
$url3 = "";

$urls = array($url1, $url2, $url3);

for($x = 0; $x < sizeof($urls); $x++){
    if(!filter_var($urls[$x], FILTER_VALIDATE_URL)){
        unset($urls[$x]);
    }
}

print_r() gives me this:

Array ( [0] => http://localhost/work/project/scrapes/1.html [2] => )

I have no idea why $urls[2] is still there, and why it's not removed.

2 Answers 2

5

Because you calculate the size() dynamically - it reduces as long as you delete elements. So the fix is to get the size before the loop:

$url1 = "http://localhost/work/project/scrapes/1.html";
$url2 = "";
$url3 = "";

$urls = array($url1, $url2, $url3);
$size = sizeof($urls); // <----

for($x = 0; $x < $size; $x++){
    if(!filter_var($urls[$x], FILTER_VALIDATE_URL)){
        unset($urls[$x]);
    }
}

var_dump($urls);
Sign up to request clarification or add additional context in comments.

1 Comment

I did not realize the size would be recalculated every iteration. Thanks!
2

That is because you are calculating the size of the array in each iteration.

By Iteration:

  1. sizeof($urls) = 3, $x = 0, $x < sizeof($urls) TRUE unset($urls[0]);

  2. sizeof($urls) = 2, $x = 1, $x < sizeof($urls) TRUE unset($urls[1]);

  3. sizeof($urls) = 1, $x = 2, $x < sizeof($urls) FALSE ... no more code executed

save the length of the array before start the loop

$length = sizeof($urls);

for($x = 0; $x < $length; $x++){
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.