Skip to content
Advertisement

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

I’m looking for an efficient function to achieve the following. Let’s say we have an array:

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

Slicing from a position should always return 5 values. 2 before the position index and 2 values after the position index – and of course, the position index itself.

If a position index is at the beginning of the array i.e. 0 (example 2), the function should return the next 4 values. Similarly, if the position index is at the end of the array (example 3), the function should return the previous 4 values.

Here’s some examples of various indexes one could pass to the function and expected results:

$index = 3; // Result: 1, 2, 3, 4, 5. *example 1
$index = 0; // Result: 0, 1, 2, 3, 4. *example 2
$index = 7; // Result: 3, 4, 5, 6, 7. *example 3
$index = 6; // Result: 3, 4, 5, 6, 7. *example 4

As represented in examples: (example 1, example 4), the function should always attempt to catch tokens succeeding and preceding the position index – where it can, whilst always returning a total of 5 values.

The function must be bulletproof to smaller arrays: i.e if $a has 4 values, instead of 5, the function should just return everything.

Advertisement

Answer

Something like this?

@edit:

Sorry, I misread your original requirement. Second attempt:

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)
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement