-1

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;
}
ehime
  • 8,025
  • 14
  • 51
  • 110

2 Answers2

1

Quoting from the PHP docs

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., 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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Agreed, the array_filter implementation doesn't seem to work much better though http://pastebin.com/iztTJpjT – ehime Feb 26 '15 at 22:49
  • 1
    Well with array_filter() you shouldn't be unsetting within the closure, simply returning a boolean true/false to indicate whether the record should be unset or not – Mark Baker Feb 26 '15 at 22:50
  • Awesome, worked amazingly, +1 and accepted. Will also publish code to show anyone else searching for this the answer. – ehime Feb 26 '15 at 22:56
1

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;
}
ehime
  • 8,025
  • 14
  • 51
  • 110