Which one would you use?
Basically I only want to get the 1st element from a array, that\'s it.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
You would use $arr[ 0 ];
array_shift
removes the first element from the array.
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon
's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset
is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0
index.array_shift
will remove and return the value which is found at reset
The OP made the assumption that $arr[0]
is the first index is not accurate in that particular context.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
array_shift
will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
with array_shif you have two operations:
if you access by index, actually you have only one operation.