What is PHP end() Function?
If you want to move the internal pointer to the last element of an array, use end() function in PHP. You’ll also get that last element as the return value of the function.
Syntax:
end(array)
Parameters:
The Function has 1 parameter which is required-
array (Required): The input array.
Return Values:
The function returns-
- The last element if the function is not empty. Check example 1.
- FALSE if the array is empty. Check example 2.
Examples:
Example 1:
<?php
$language = ["PHP", "Python", "Java", "SQL", "HTML", "CSS", "JavaScript"];
$last_element = end($language);
echo "The last element of the array is: " . $last_element;
?>
Output:
The last element of the array is: JavaScript
Example 2:
<?php
$language = [];
$last_element = end($language);
echo "The last element of the array is: ";
var_dump( $last_element);
?>
Output:
The last element of the array is: bool(false)
Caution:
The function modifies the internal pointer of the original array by moving it to the last element. So, if you perform other pointer related functions like current(), next(), prev() with this function, you may get the wrong element.
Alternative to PHP end() Function:
- If you want to get the last value of an array, use array_last() function. It was introduced in PHP version 8.5.
- If you want to get the last element of an array without changing internal pointer’s location, use array_key_last() function to get the last key of the array, then you can use it to get its value.
- If you just want to retrieve the last element from an array and you have no problem even the function removes the element, use array_pop() function.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP end() Function
The end() function is a built-in PHP function and part of the PHP’s array functions. It is a quick way to move the internal pointer to the last element.