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

Is there a way to save only the first N (e.g. 10) elements of an array? I know there is array_pop , but is there a better, more elegant way?

+7
source share
1 answer

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 elements of $a and returns them, while array_splice itself modifies $a and returns only those elements that were removed from $a .

+23
source

All Articles