How to Get the First 5 Elements of Array in PHP?
To obtain the first 5 elements of a PHP array, you can use the array_slice() function.

When working with PHP arrays, there may be instances where you need to extract the initial 5 elements from an array. This guide demonstrates how to efficiently accomplish this task in PHP. Let's delve into the steps for achieving this.
To obtain the first 5 elements of a PHP array, you can use the array_slice()
function. Here's a straightforward example:
// Sample PHP array
$data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
// Use array_slice() to extract the first 5 elements
$firstFive = array_slice($data, 0, 5);
// Display the first 5 elements
print_r($firstFive);
In this example, we start with a PHP array named $data
, which contains a sequence of numbers. We employ the array_slice()
function to extract the first 5 elements from the array. This function accepts three arguments: the input array, the starting index (0 in this case), and the length (5 in this case).
The output will be an array containing the first 5 elements:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
[4] => 50
)