PHP array slice from position + attempt to return fixed number of items



PHP Snippet 1:

function get_slice_of_5($index, $a) {
   if ($index+2 >= count($a)) {
     return array_slice($a, -5, 5)
   }
   else if($index-2 <= 0) {
          return array_slice($a, 0, 5)  
   }
   else return array_slice($a, $index-2, 5)
}

PHP Snippet 2:

$a = [0, 1, 2, 3, 4, 5, 6, 7];


$index = 3; // Result: 1, 2, 3, 4, 5. *example 1
echo pages($a, $index) . "\n";

function pages($a, $index){

    if($index >= count($a)-2){
        $start = count($a)-5; // index is at end of array
    }elseif($index <=2){
        $start = 0; // index is at start
    }else{
        $start = $index-2; // index is somewhere in the middle
    }
    return implode(", ", array_slice($a, $start, 5));

}

PHP Snippet 3:

$a = [1,2,3,4,5,6,7,8,9];

echo "<pre>"; print_r(array_slicer($a, 2));

function array_slicer($arr, $start){

    // initializations
    $arr_len = count($arr);
    $min_arr_len = 5; // the size of the spliced array
    $previous_elements = 2; // number of elements to be selected before the $start
    $next_elements = 2; // number of elements to be selected after the $start
    $result = [];

    // if the $start index doesn't exist in the given array, return false!
    if($start<0 || $start>=$arr_len){
        return false;
    } elseif($arr_len <= $min_arr_len){ // if the size of the given array is less than the d size of the spliced array, return the whole array!
        return $arr;
    }

    // check if the $start has less than ($previous_elements) before it
    if($arr_len - ($arr_len - $start) < $previous_elements){

        $next_elements += ($next_elements - ($arr_len - ($arr_len - $start)));

    } elseif(($arr_len - 1 - $start) < $next_elements){ // check if the $start has less than ($next_elements) after it

        $previous_elements += ($previous_elements - ($arr_len - 1 - $start));

    }

    for($i = ($start-$previous_elements); $i <= ($start + $next_elements); $i++){
        if($i>-1 && $i<$arr_len){
            $result[] = $arr[$i];
        }
    }   

    return $result;
}

PHP Snippet 4:

array_slice($a, min(count($a) - 5, max(0, $index - 2)), 5)

PHP Snippet 5:

$a = [0, 1, 2, 3, 4, 5, 6, 7];
$count = count($a);
$span = 5; // most sensible with odd numbers
$center = (int)($span / 2);

foreach ($a as $i => $v) {
    printf(
        "%d: %s\n",
        $i,
        implode(
            ',',
            array_slice(
                $a,
                min($count - $span, max(0, $i - $center)),
                $span
            )
        )
    );
}

PHP Snippet 6:

0: 0,1,2,3,4
1: 0,1,2,3,4
2: 0,1,2,3,4
3: 1,2,3,4,5
4: 2,3,4,5,6
5: 3,4,5,6,7
6: 3,4,5,6,7
7: 3,4,5,6,7