Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only keep the first N elements of an array in PHP?

Tags:

arrays

php

Is there a way to only keep the first N (for example 10) elements of an array? I know there is array_pop, but is there a better, more elegant way?

like image 331
EOB Avatar asked Feb 06 '12 14:02

EOB


People also ask

Which function returns an array with the first N elements of the data set?

In Spark, the take function behaves like an array. It receives an integer value (let say, n) as a parameter and returns an array of first n elements of the dataset.

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How do you select the first element of an array?

Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

How can I display the first element of an array in PHP?

Get the First Element of an Array in PHP Just get the element with index 0! echo $names [0];


1 Answers

You can use array_slice or array_splice:

$b = array_slice($a, 0, 10);
$c = array_splice($a, 0, 10);

Note that array_slice copies the items of $a and returns them while array_splice does modify $a itself and only returns the items that have been removed from $a.

like image 115
Gumbo Avatar answered Oct 02 '22 01:10

Gumbo