ConFoo Montreal 2026: Call for Papers

Voting

: max(two, seven)?
(Example: nine)

The Note You're Voting On

nigra
7 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($count, $key = null, $arRelated = array(), $cntRelated = 2)
{
if(
$count > 0 && isset($key))
{
$keyL = $count - 1;
$keyR = 1;
$arResult = array();
for(
$i = 1; $i <= $cntRelated; $i++)
{
if(
$key == 0)
{
if((
$i % 2) == 0)
{
$curKey = $count - $keyL;
$keyL--;
}
else
{
$curKey = $count - $keyR;
$keyR++;
}
}
else
{
if(
$arRelated[$i] >= $count - 1)
{
$curKey = 0;
}
else
{
$curKey = $arRelated[$i] + 1;
}
}
$arResult[$i] = $curKey;
}
return
$arResult;
}
}

$arr = range(0, 4);
$count = count($arr);

foreach(
$arr as $key => $v)
{
if(
$arRelated = array_neighbor($count, $key, $arRelated))
{
$arHeighbor[$key]['RELATED'] = $arRelated;
}
}

echo
'<pre>';print_r($arHeighbor); echo '</pre>';
?>
Array
(
[0] => Array
(
[RELATED] => Array
(
[1] => 4
[2] => 1
)

)

[1] => Array
(
[RELATED] => Array
(
[1] => 0
[2] => 2
)

)

[2] => Array
(
[RELATED] => Array
(
[1] => 1
[2] => 3
)

)

[3] => Array
(
[RELATED] => Array
(
[1] => 2
[2] => 4
)

)

[4] => Array
(
[RELATED] => Array
(
[1] => 3
[2] => 0
)

)

)

<< Back to user notes page

To Top