phpunset

PHP unset not removing value from array loop


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?


Solution

  • 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 a for() loop, but you can also simply use a foreach():

    $search_array = array("https", "www", "stackoverflow", "com");
    
    foreach($search_array as $i => $domain) { 
        if (
            $domain == null ||
            $domain == "http" && count($search_array) > 1 ||
            $domain == "https" && count($search_array) > 1 ||
            $domain == "www" && count($search_array) > 1 ||
            $domain == "com" && count($search_array) > 1
        ) { 
            unset($search_array[$i]);
        }
    }
    
    die(print_r($search_array));
    

    Output from this approach is:

    Array ( [2] => stackoverflow )