简体   繁体   中英

array_walk only partially removes matches

Ran into a weird situation were using array_walk() will only partially remove matches from my method, not certain exactly what is going on. I am currently using PHP v5.6.4. The issue almost seems to be that it is only removing every secondary match.

The kerning function

private function strip(array $exceptions)
{
    array_walk($this->hosts, function($v, $k) USE ($exceptions)
    {
        foreach ($exceptions AS $exception)
        {
            if (preg_match("/{$exception}/i", strtolower($k)))
            {
                unset($this->hosts[$k]); break;
            }
        }
    });
    print_r($this->hosts); die;
}

Quoting from the PHP docs

Only the values of the array may potentially be changed; its structure cannot be altered, ie, the programmer cannot add, unset or reorder elements . If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

my emphasis

This worked in conjunction with the information provided by Mark Baker, thanks Mark.

private function strip(array $exceptions)
{
    $this->hosts = array_filter($this->hosts, function ($k) USE ($exceptions)
    {
        foreach ($exceptions AS $exception)
        {
            if (preg_match("/{$exception}/i", strtolower($k)))

                return false;
        }
        return true;
    }, ARRAY_FILTER_USE_KEY);

    return $this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM