Break array_walk from anonymous function

Vlad Preda picture Vlad Preda · Jul 25, 2013 · Viewed 8.4k times · Source

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.

Answer

Anthony Sterling picture Anthony Sterling · Jul 25, 2013

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)
*/