Last active
May 29, 2017 09:13
-
-
Save mlebkowski/5c7dc9be4492b458ee1536dbbc2353d2 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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