从匿名函数中打破array_walk [英] Break array_walk from anonymous function

查看:62
本文介绍了从匿名函数中打破array_walk的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从匿名函数内部阻止array_walk?

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.

使用break/continue不起作用(错误:Fatal error: Cannot break/continue 1 level in ...).

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.

推荐答案

如上所述,理论上是可能的,但我建议不要这样做.这是使用异常突破array_walk的方法.

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

这篇关于从匿名函数中打破array_walk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆