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

查看:23
本文介绍了从匿名函数中打破 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 不起作用(错误:致命错误:无法在 ... 中中断/继续 1 个级别).

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天全站免登陆