Skip to content

Instantly share code, notes, and snippets.

@madfriend
Created August 22, 2012 18:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madfriend/3428257 to your computer and use it in GitHub Desktop.
Save madfriend/3428257 to your computer and use it in GitHub Desktop.
PHP loop API
<?php
function loop($count, $callback) {
if (is_int($count)) {
for ($i = 0; $i < $count; $i++) {
$callback($i);
}
}
elseif(is_array($count)) {
$_copy = $count;
while($v = array_shift($_copy)) $callback($v);
}
elseif(is_callable($count)) {
while($r = $count()) $callback($r);
}
}
loop(5, function() {
print "I'm new here.\n";
});
loop(3, function($i) {
loop(3, function($z) use ($i) {
print "$i : $z\n";
});
});
loop([2, 3, 4, 5], function($v) {
print "This is $v.\n";
});
loop(
function() {
static $cnt = 0;
$cnt++;
return $cnt > 5 ? NULL : $cnt;
},
function($v) {
print "I was called.\n";
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment