PHP: Get last element of array
Often you need to get the last element of PHP array. This is easy to achieve with using count() function, wich counts all elements in array. Because PHP arrays are indexed from 0, you must remeber to get "count()-1" element of an array, not "count()" element:
$exampleArray = array( 3,6,8,11,14 ); $lastElement = $array[ count($exampleArray) - 1]; echo $lastElement; // prints 14
This is the obvious way for some begginer developers. But more experienced developers will know, that there is a function defined especially for this purpose: echo end( $exampleArray ); // prints 14
Because this function will move internal array pointer to the end, you can reset it if you are currently iterating over this orray, for example: reset( $exampleArray ); // prints 14
If you are afraid about non set array, or set as other type than array, you can use function is_array() to check if this variable is defined as array. You can also get a last key of an array in several ways: echo end(array_keys( $exampleArray) ); // or: end( $exampleArray ); echo key( $exampleArray );
If you don't want to move internal array pointer, you can use another one-liner to get last element from array: $last = array_slice($array, -1, 1, true);
Comments
Post a Comment