Break array_walk from anonymous function

亡梦爱人 提交于 2019-12-04 02:48:47

问题


Is there a way to stop an array_walk from inside the anonymous function ?

Here is some sample code (that works) to show what I mean, that checks if an array has only numeric values.

$valid = true;
array_walk($parent, function ($value) use (&$valid) {
    if (!is_numeric($value)) {
        $valid = false;
    }
});

return $valid ? 'Valid' : 'Invalid';

If I have a big enough array, and the first entry is invalid, the rest of the (redundant) checks are still done, so I would like to stop the execution.

Using break / continue doesn't work (error: Fatal error: Cannot break/continue 1 level in ...).

Note: I don't want to rewrite the code, I just want to know IF this is possible.


回答1:


As stated, theoretically it's possible but I'd advise against it. Here's how to use an Exception to break out of the array_walk.

<?php
$isValid = false;

$array = range(1, 5);

try {
    array_walk($array, function($value) {
        $isAMagicNumber = 3 === $value;
        if ($isAMagicNumber) {
            throw new Exception;
        } 
    });
}catch(Exception $exception) {
    $isValid = true;
}

var_dump($isValid);

/*
    bool(true)
*/



回答2:


You can put a static flag inside the anonymous function:

array_walk($ary, function($item) {
    static $done = false;
    if($done) {
        return;
    }

    // … your code

    if($myBreakCondition) {
        $done = true;
        return;
    }
});

This doesn’t actually stop the iteration, but all further cycles after the flag is set simply do nothing. Not very efficient, but it might work without any greater performance impact if the arrays iterated are not too large.

In your case, the code would be:

$valid = true;
array_walk($parent, function($value) use(&$valid) {
    static $done = false;
    if($done) {
        return;
    }

    if(!is_numeric($value)) {
        $valid = false;
        $done = true;
        return;
    }
});
return $valid ? 'Valid' : 'Invalid';

But actually it won’t be much difference if there was no “break” at all. Only the “false” would be assigned for every invalid value, which does not matter as the result would be still false. Maybe it would be even more efficient that my static variable cheat.

Personally in your case I would use array_filter instead:

$valid = count(array_filter($parent, 'is_numeric')) == count($parent);

or just

$valid = array_filter($parent, 'is_numeric')) == $parent;

If all values in the $parent array are numeric, they would be all present after the filtering. On the other hand, any non-numeric value in the array would affect the contents (decreasing the item count) in the filtered array and the comparison would yield false.



来源:https://stackoverflow.com/questions/17853113/break-array-walk-from-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!