dh762
dh762

Reputation: 2429

Return false if one call returns false in a function

This is a basic logic question: I have a function that should return true if all methods/queries return true. However, with this approach here, the whole function can return true when the last foreach call returns true – how do I prevent this?

function deleteAllSuccess(){
    $all_query_ok = true;
    $params = array('A', 'B', 'C');

    deleteOne() ? null : $all_query_ok = false;
    deleteTwo() ? null : $all_query_ok = false;

    foreach($params as $p){
        $all_query_ok = deleteThree($p);
        $all_query_ok = deleteFour($p);
    }

   if($all_query_ok){
       commit();
       return true;
   }else{
       rollback();
       return false;
}

Upvotes: 0

Views: 517

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

The simple solution would be to use the & operator if you want every function to execute (or the && operator for short-circuiting):

foreach($params as $p){
    $all_query_ok = $all_query_ok & deleteThree($p);
    $all_query_ok = $all_query_ok & deleteFour($p);
}

return $all_query_ok;

Or for brevity, you can use the &= compound assignment operator:

foreach($params as $p){
    $all_query_ok &= deleteThree($p);
    $all_query_ok &= deleteFour($p);
}

But in case you want to exit the function as soon as any of the functions return false, you can do something like this:

if (!deleteOne()) return false;
if (!deleteTwo()) return false;

foreach($params as $p){
    if (!deleteThree($p)) return false;
    if (!deleteFour($p)) return false;
}

return true;

Upvotes: 2

Related Questions