How to extract a slice of elements from an array in PHP?

To extract a slice of elements from an array in PHP, you can use the array_slice() function.

The array_slice() function returns a portion of an array, starting from the specified offset and containing the specified length of elements.

Here's the syntax:

array_slice($array, $offset, $length);

Parameters:

  • $array: The input array from which the slice will be extracted.
  • $offset: The index to start the slice from. If the offset is a negative number, it starts counting from the end of the array.
  • $length (optional): The number of elements to include in the slice. If this parameter is omitted, the slice will include all elements from the offset to the end of the array.

Example usage:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $slice = array_slice($array, 2, 4); // Output: [3, 4, 5, 6] print_r($slice);

In the above example, the array_slice() function is used to extract a slice of 4 elements starting from the index 2. The resulting slice is then printed using print_r().