Voting

: zero minus zero?
(Example: nine)

The Note You're Voting On

lukasz at karapuda dot com
20 years ago
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
$keys = array_keys($arr);
$keyIndexes = array_flip($keys);

$return = array();
if (isset(
$keys[$keyIndexes[$key]-1])) {
$return[] = $keys[$keyIndexes[$key]-1];
}
else {
$return[] = $keys[sizeof($keys)-1];
}

if (isset(
$keys[$keyIndexes[$key]+1])) {
$return[] = $keys[$keyIndexes[$key]+1];
}
else {
$return[] = $keys[0];
}

return
$return;
}
?>

<< Back to user notes page

To Top