Last active
September 19, 2017 12:25
-
-
Save dave1010/21f8e64974e2ac618f02 to your computer and use it in GitHub Desktop.
array_map in php, with break
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BreakOut extends Exception {} | |
function mapGenerator(array $arr, $callback) | |
{ | |
$ret = []; | |
foreach ($arr as $val) { | |
try { | |
yield $callback($val); | |
} catch (BreakOut $e) { | |
return; | |
} | |
} | |
} | |
$a = range(1, 10); | |
$callback = function($val) { | |
if ($val > 5) { | |
throw new BreakOut; | |
} | |
return $val * $val; | |
}; | |
foreach (mapGenerator($a, $callback) as $v) { | |
echo $v . PHP_EOL; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BreakOut extends Exception {} | |
function map(array $arr, $callback) | |
{ | |
$ret = []; | |
foreach ($arr as $val) { | |
try { | |
$ret[] = $callback($val); | |
} catch (BreakOut $e) { | |
break; | |
} | |
} | |
return $ret; | |
} | |
$a = range(1, 10); | |
$callback = function($val) { | |
if ($val > 5) { | |
throw new BreakOut; | |
} | |
return $val * $val; | |
}; | |
print_r(map($a, $callback)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment