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?
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.
The array_keys() function returns an array containing the keys.
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.
Get the First Element of an Array in PHP Just get the element with index 0! echo $names [0];
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With