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?
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 returnstrueorfalse, you could shorten it up to something like this: