Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function array_to_entries(array $array) {
return array_map(function ($key, $value) {
return [
"key" => $key,
"value" => $value,
];
}, array_keys($array), array_values($array));
}
function findNextItem(array $input, $currentKey, $loop = false) {
return array_reduce(array_to_entries($input), function (array $context, $item) use ($currentKey){
return [
"isCurrent" => $item["key"] === $currentKey,
"value" => $context["isCurrent"] ? $item["value"] : $context["value"],
];
}, [
"isCurrent" => false,
"value" => $loop ? reset($input) : null,
])["value"];
}
function findPrevItem(array $input, $currentKey, $loop = false) {
return findNextItem(array_reverse($input), $currentKey, $loop);
}
var_dump(
findNextItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'alpha') === 2,
findNextItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'bravo') === 3,
findNextItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'charlie') === null,
findNextItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'charlie', true) === 1,
findNextItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'not found') === null,
findPrevItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'alpha') === null,
findPrevItem(['alpha' => 1, 'bravo' => 2, 'charlie' => 3], 'alpha', true) === 3
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.