Created
November 22, 2011 10:35
-
-
Save firegate666/1385386 to your computer and use it in GitHub Desktop.
extended foreach method with extra information about first and last elements, number of elements, actual index
This file contains hidden or 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 | |
/** | |
* Call callback function for every element of an array and provide some extra information for each element | |
* | |
* @param array $array | |
* @param Callback/Closure $callback | |
* Callback/Closure must have 6 parameters | |
* mixed key: key of item | |
* mixed value: value of item | |
* integer counter: human readable index of item; starts with 1 | |
* integer index: index of item; starts with 0 | |
* integer num: totalcount of elements | |
* boolean first: is first element | |
* boolean last: is last element | |
*/ | |
function foreachExt($array, $callback) | |
{ | |
$num = count($array); | |
$counter = 1; | |
foreach($array as $k=>$v) | |
{ | |
$first = $counter == 1; | |
$last = $counter == $num; | |
call_user_func_array($callback, array($k, $v, $counter, $counter-1, $num, $first, $last)); | |
$counter++; | |
} | |
} | |
/* | |
* example usage | |
*/ | |
$array = array('First', 'Middle 1', 'Middle 2', 'Middle 3', 'Last'); | |
foreachExt($array, function($k, $v, $counter, $index, $num, $first, $last) | |
{ | |
var_dump($k, $v, $counter, $index, $num, $first, $last); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment