Skip to content

Instantly share code, notes, and snippets.

@emrahoruc
Forked from dave1010/array-map-break-yield.php
Created September 19, 2017 12:25
Show Gist options
  • Save emrahoruc/ae541179ea968468695a1ed083c82066 to your computer and use it in GitHub Desktop.
Save emrahoruc/ae541179ea968468695a1ed083c82066 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