开发者

Getting the overall return value of a function within a loop

开发者 https://www.devze.com 2022-12-15 06:12 出处:网络
What I am doing is looping over an array and running a function on each value of the array (the function returns true on success, false on error). I would like to return false if any of the calls insi

What I am doing is looping over an array and running a function on each value of the array (the function returns true on success, false on error). I would like to return false if any of the calls inside the loop returned false, but I want the whole loop to be processed.

Probably easier to explain with code:

foreach($this->_cacheLocations as $cacheId)开发者_开发百科
{
    $this->deleteCache($cacheId);
}

return true/false depending on whether anything failed above;

I'd prefer not to introduce a variable to keep track of any falses if possible. Eg, I'd prefer not to do the following:

$result = true;
foreach($this->_cacheLocations as $cacheId)
{
    $_result = $this->deleteCache($cacheId);
    if(!$_result) $result = false;
}

return $result;

Is there a fancy way to do this or should I just do it the second way?


I would go with a variable, like you did in your second portion of code -- at least, that's what I do in that kind of situations.


If you want to eliminate one temporary variable, you could use :

$result = true;
foreach($this->_cacheLocations as $cacheId)
{
        if (!$this->deleteCache($cacheId)) {
            $result = false;
        }
}
return $result;

But the idea remains the same as what you posted.


In order to track multiple return results together, you're unfortunately going to need a variable. If you didn't want it to be a local variable in the scope of your loop, you could create an object property that was set by deleteCache(), but unless it's being used by other functions as well, a local variable is the cleanest solution.

Assuming that $this->deleteCache() always returns true or false, you could shorten it up to something like this:

$result = true;
foreach($this->_cacheLocations as $cacheId)
{
        $result = $this->deleteCache($cacheId) && $result;
}
return $result;
0

精彩评论

暂无评论...
验证码 换一张
取 消