3v4l.org

run code in 300+ PHP versions simultaneously
<?php function tryMultiple(callable $func, int $count=3, array $acceptable=['\Throwable']) { $success = false; for($i=0; $i<$count; $i++) { try { $v = $func(); $success = true; break; } catch(\Throwable $t) { $is_ok = false; foreach($acceptable as $accept) { if( is_a($t, $accept) ) { $is_ok = true; } } if( ! $is_ok ) { throw $t; } } } if($success) { return $v; } else { throw new \Exception("Failure count exceeded limit of $count.", 42, $t); } } $always_throws = function(){throw new \Exception('bork');}; $always_works = function(){return 'work';}; var_dump(tryMultiple($always_works)); try { tryMultiple($always_throws); } catch(Exception $e) { var_dump($e->getMessage()); } try { tryMultiple($always_throws, 3, []); } catch(Exception $e) { var_dump($e->getMessage()); }

preferences:
45.53 ms | 402 KiB | 5 Q