0

I wonder if there is a way to break the rest of walking through an array when you found your desired result:

array_walk($arr, function($value, $key)
{
    if($value == "test")
    {
        global $id;
        $id = $key;
        break; // I know that break doesn't work! that's just for example.
    }
});

The above example shows what I mean by jumping out from array_walk

revo
  • 47,783
  • 14
  • 74
  • 117

1 Answers1

5

Based in this answer (https://stackoverflow.com/a/17853359/2112743) you could break the function with a cached exception:

try {
    array_walk($arr, function($value, $key)
    {
        if($value == "test")
        {
            global $id;
            $id = $key;
            throw new Exception;
        }
    });
} catch (Exception $e) {
    //
}

// Rest of your code

Although I would also recommend you to use a normal breakable loop.

Good luck;


EDIT

This may be a solution as well, more semantic. This doesn't break the closure, but run the conditional just once. Also gets rid of that nasty global.

$array = array(1,2,3,'test',5,6,7,8,9,10);
$stop = false;
$id = 0;
array_walk($array, function($value, $key) use ($stop, &$id){
    if (!$stop && $value == 'test') {
        $id = $key;
        $stop = true;
        echo $id;
    }
});
// This just echo 3;
Community
  • 1
  • 1
Axel A. García
  • 683
  • 9
  • 21
  • 2
    Wow. While that *is* a solution, I would never suggest it. This is like using a jackhammer to hammer a picture frame hook. – gen_Eric Dec 10 '13 at 19:47
  • Yes, you're definitely right is like using a gun to turn on a TV (http://www.youtube.com/watch?v=eSLMo-lnsjg‎), but just for the sake of knowledge. – Axel A. García Dec 10 '13 at 19:50
  • Haha. This is actually pretty funny :D In fairness, I think Axel has flagged this appropriately as not recommended. +1 – Darragh Enright Dec 10 '13 at 19:54
  • If you *must* use `array_walk` (for whatever reason), then `$stop = TRUE;` is a decent solution. `array_walk` might not be the right tool here though. – gen_Eric Dec 10 '13 at 20:54
  • I'd suggest doing `if(!$stop && $value == 'test'){` instead. That way it won't compare `$value` after it already found it. – gen_Eric Dec 10 '13 at 20:55