I have an array with specific keys:
array(
420 => array(...),
430 => array(...),
555 => array(...)
)
In my applicati
This is a simple solution for taking previous and next items, even if we are at the ends of the array.
<?php
$current_key; // the key of the item we want to search from
if (isset($array[$current_key+1]))
{
// get the next item if there is
$array_next = $array[$current_key+1];
}
else
{
// if not take the first (this means this is the end of the array)
$array_next = $array[0];
}
if (isset($array[$current_key-1]))
{
// get the previous item if there is
$array_prev = $array[$current_key-1];
}
else
{
// if not take the last item (this means this is the beginning of the array)
$array_prev = $array[count($array)-1];
}
Expanding further on the solution of Luca Borrione and cenk, so that you can wrap around the end of the array in either direction, you may use:
function getAdjascentKey($key, $hash = array(), $increment) {
$keys = array_keys($hash);
$found_index = array_search($key, $keys);
if ($found_index === min(array_keys($keys)) && $increment === -1) {
$found_index = max(array_keys($keys))+1;
}
if ($found_index === max(array_keys($keys)) && $increment === +1) {
$found_index = min(array_keys($keys))-1;
}
return $keys[$found_index+$increment];
}
You can iterate through the array in reverse and return the next iteration after finding the search value.
$found = false;
foreach(array_reverse($array, true) as $key=>$value) {
if ($found) {
print "$key => $value\n";
break;
} else if ($key == 555) {
$found = true;
}
}
http://ideone.com/2WqmC