Array Slicing

Array slicing allows you to extract a portion of the array.

It takes two parameters: the starting index and the ending index (optional). It returns a new array containing the extracted portion.

Let's perform such operations on the array ['cat', 'dog', 'fish', 'turtle', 'parrot']. Its structure is the following:

array-slicing-structure

Two arguments slicing

Positive argument slicing

If the second argument is a positive number, it skips the first couple of elements.

Output:

In this example, array_slice($elements, 2) skips the first 2 elements of the array - 'cat' and 'dog'.

The remaining part of the array (starting from the 3rd element) is extracted - ['fish', 'turtle', 'parrot'].

Negative argument slicing

If the second argument is a negative number, it tracks the elements in reverse.

positive-and-negative-argument-slicing

Output:

In this example, array_slice($elements, -3) extracts only the last 3 elements of the array - 'fish', 'turtle', and 'parrot'.

Three arguments slicing

Positive arguments slicing

If the third argument is a positive number, it specifies how many elements must be taken.

Output:

In this example, array_slice($elements, 2, 3) skips the first 2 elements of the array - 'cat' and 'dog'.

Afterwards, it takes 3 elements (specified by the third argument - 3) - 'fish', 'turtle', 'parrot'.

Negative arguments slicing

If the third argument is a negative number, it specifies which must be the end negative index.

Output:

In this example, array_slice($elements, -4, -2) starts slicing at the 4th element counting backwards and ends before the 2nd element counting backwards.

Mixed arguments slicing

Both positive and negative arguments can be specified.

Output:

In this example, array_slice($elements, 1, -1) starts after the first element and ends before the last element.

Invalid cases

An invalid case simply returns an empty array. In such cases, the slicing start argument position is after the slicing end (for negative third argument).

Example of valid and invalid cases:

Output:

Another invalid slicing case is specifying a starting argument that's beyond the array's bounds:

Output: