I'm frequently using the following to get the second to last value in an array:
$z=array_pop(array_slice($array,-2,1));
Am I missing a php function to do that in one go or is that the best I have?
Referring to array elements You can refer to the first element of the array as myArray[0] , the second element of the array as myArray[1] , etc… The index of the elements begins with zero. Note: You can also use property accessors to access other properties of the array, like with an object.
To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
end($array);
$z = prev($array);
This is more efficient than your solution because it relies on the array's internal pointer. Your solution does an uncessary copy of the array.
For numerically indexed, consecutive arrays, try $z = $array[count($array)-2];
Edit: For a more generic option, look at Artefecto's answer.
Or here, should work.
$reverse = array_reverse( $array );
$z = $reverse[1];
I'm using this, if i need it :)
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