Skip to content

Instantly share code, notes, and snippets.

@oschonrock
Last active Dec 7, 2017
Embed
What would you like to do?
leach() = "legacy each": php72 compat for deprecated each(). Use to refactor tired third party libs, when not performance critical.
<?php
/**
* leach() = "legacy each"
*
* replacement for deprecated each() for php7.2
* use this if refactoring would be too painful and performance is not relevant
*
*/
function leach(&$arr)
{
$k = key($arr);
if ($k === null)
{
// https://secure.php.net/manual/en/function.each.php
// If the internal pointer for the array points past the end of
// the array contents, each() returns FALSE.
return false;
}
else
{
$v = current($arr);
// After each() has executed, the array cursor will be left on the
// next element of the array, or past the last element if it hits the
// end of the array.
next($arr);
// Returns the current key and value pair from the array
// array. This pair is returned in a four-element array, with the
// keys 0, 1, key, and value. Elements 0 and key contain the key
// name of the array element, and 1 and value contain the data.
return [
1 => $v,
'value' => $v,
0 => $k,
'key' => $k
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment