Skip to content

Instantly share code, notes, and snippets.

@dave1010
Last active September 19, 2017 12:25
Show Gist options
  • Save dave1010/21f8e64974e2ac618f02 to your computer and use it in GitHub Desktop.
Save dave1010/21f8e64974e2ac618f02 to your computer and use it in GitHub Desktop.
array_map in php, with break
<?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;
}
<?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