Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: zero plus seven?
(Example: nine)

The Note You're Voting On

court shrock
21 years ago
This code returns neighbors of the specified key. The result will be empty if it doesn't have any neighbors. My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array. Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
krsort($arr);
$keys = array_keys($arr);
$keyIndexes = array_flip($keys);

$return = array();
if (isset(
$keys[$keyIndexes[$key]-1]))
$return[] = $keys[$keyIndexes[$key]-1];
if (isset(
$keys[$keyIndexes[$key]+1]))
$return[] = $keys[$keyIndexes[$key]+1];

return
$return;
}

?>

<< Back to user notes page

To Top