Created
August 22, 2012 18:43
-
-
Save madfriend/3428257 to your computer and use it in GitHub Desktop.
PHP loop API
This file contains 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 | |
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