Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).
PHP lets you create 2 types of array: Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0 , the second has an index of 1 , and so on.
JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .
To remove the first element or value from an array, array_shift() function is used. This function also returns the removed element of the array and returns NULL if the array is empty.
Well, they do different things.
array_shift($arr)
takes the first element out of the array, and gives it to you.
$arr[0]
just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr)
. This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
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