I have an array with specific keys:
array(
420 => array(...),
430 => array(...),
555 => array(...)
)
In my applicati
@Luca Borrione's solution was helpful. If you want to find both previous and next keys, you may use the following function:
function getAdjascentKey( $key, $hash = array(), $increment ) {
$keys = array_keys( $hash );
$found_index = array_search( $key, $keys );
if ( $found_index === false ) {
return false;
}
$newindex = $found_index+$increment;
// returns false if no result found
return ($newindex > 0 && $newindex < sizeof($hash)) ? $keys[$newindex] : false;
}
Usage:
// previous key
getAdjascentKey( $key, $hash, -1 );
// next key
getAdjascentKey( $key, $hash, +1 );
Examples:
$myhash = array(
'foo' => 'foovalue',
'goo' => 'goovalue',
'moo' => 'moovalue',
'zoo' => 'zoovalue'
);
getAdjascentKey( 'goo', $myhash, +1 );
// moo
getAdjascentKey( 'zoo', $myhash, +1 );
// false
getAdjascentKey( 'foo', $myhash, -1 );
// false