Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@TheMadDeveloper
Last active July 2, 2016 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheMadDeveloper/71b300211686cc9da1a90a05e4e0a86a to your computer and use it in GitHub Desktop.
Save TheMadDeveloper/71b300211686cc9da1a90a05e4e0a86a to your computer and use it in GitHub Desktop.
PHP sample iterating over an array or hash with efficient special processing on first and last element
<?php
# Iterates through the supplied hash or array with optional special processing on first and last element.
# PARAMETERS:
# $list: the hash or array to iterate over
# $fnMain: function($listElement) which should process the list elements
# $fnFirst: function($listElement) which should process the FIRST element in the list
# if null, no special processing is done, and the first element will be processed with $fnMain
# $fnLast: function($listElement) which should process the LAST element in the list
# if null, no special processing is done, and the last element will be processed with $fnMain
function iterateList($list, $fnMain, $fnFirst, $fnLast) {
$arr = array_keys($list);
$numItems = count($arr);
if ($numItems == 0) {
return;
};
$i=0;
if (is_callable($fnFirst)) {
$firstItem=$list[$arr[0]];
call_user_func($fnFirst, $firstItem);
$i++;
}
while($i<$numItems-1){
$someItem=$list[$arr[$i]];
call_user_func($fnMain, $someItem);
$i++;
}
$lastItem=$list[$arr[$i]];
call_user_func((is_callable($fnLast) ? $fnLast : $fnMain), $lastItem);
$i++;
}
######### END FUNCTION ###########
# EXAMPLE USAGE
$handleItem = function($item) {
echo("<div>".$item."</div>");
};
$handleFirst = function($item) {
echo("<div>FIRST: ".$item."</div>");
};
$handleLast = function($item) {
echo("<div>LAST: ".$item."</div><br/>");
};
$objarr = array('one' => "1 1 1", 4 => 'Four', 9 => 9, 8 => 'Eight');
iterateList($objarr, $handleItem, $handleFirst, $handleLast);
iterateList([4, 3, 2, 1], $handleItem, null, $handleLast);
iterateList($objarr, $handleItem, $handleFirst, null);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment