Break array_walk from anonymous function

后端 未结 2 1969
我在风中等你
我在风中等你 2021-01-17 09:26

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, th

相关标签:
2条回答
  • 2021-01-17 10:10

    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.

    0 讨论(0)
  • 2021-01-17 10:18

    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)
    */
    
    0 讨论(0)
提交回复
热议问题