Break array_walk from anonymous function Break array_walk from anonymous function php php

Break array_walk from anonymous function


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


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.