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:

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement