Skip to content

Instantly share code, notes, and snippets.

@krmgns
Last active October 28, 2022 09:47
Show Gist options
  • Save krmgns/30dd2bf8b22329a2dbc11a045aed3859 to your computer and use it in GitHub Desktop.
Save krmgns/30dd2bf8b22329a2dbc11a045aed3859 to your computer and use it in GitHub Desktop.
Polyfill for "each" function that was removed as of PHP/8
<?php
if (!function_exists('each')) {
function each(array &$array) {
$value = current($array);
$key = key($array);
if (is_null($key)) {
return false;
}
// Move pointer.
next($array);
return array(1 => $value, 'value' => $value, 0 => $key, 'key' => $key);
}
}
/*
// Yields same results with the samples on docs: https://php.net/each
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
print_r(each($foo));
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
print_r(each($foo));
print_r(each($foo));
print_r(each($foo)); // false
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
*/
@krmgns
Copy link
Author

krmgns commented Mar 17, 2021

You should move this into a real composer package.

@donatj

I already did, see https://github.com/craftgate/craftgate-php-client/pull/14/files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment