How to Get First 5 Elements of Array in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hey Artisan,

Here, I will show you php array get first 5 elements. let’s discuss about php array get 5 first element value. you can see how to get 5 first element of array in php. This post will give you a simple example of php get 5 first key of array example. Alright, let’s dive into the details.

we will use array_slice() function to get first 5 elements of array in php. so, let's see the simple code of how to get first 5 values in php array.

Example:

index.php

<?php

$myArray = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];

$firstElems = array_slice($myArray, 0, 5);

var_dump($firstElems);

?>

Output:

array(5) {

[0]=> string(3) "One"

[1]=> string(3) "Two"

[2]=> string(5) "Three"

[3]=> string(4) "Four"

[4]=> string(4) "Five"

}

I hope it can help you...

Tags :
Shares