views:

72

answers:

2

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?

+3  A: 

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.

Pascal MARTIN
agreed, no hacks around this one.
cballou
A good answer. Thank you.
Blair McMillan
You're welcome :-) Have fun !
Pascal MARTIN
+2  A: 

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;
zombat
Thanks, this is certainly cleaner than what I had.
Blair McMillan
Javier
Excellent point Javier, you are correct. I reversed the order of operations to fix it. Thanks.
zombat
Thanks for that Javier.
Blair McMillan