PHP end Function | Get the Last Element in Array

PHP end is an inbuilt function in PHP. It returns the last element of the array. Also, it sets the internal pointer to the last element of the array. It works opposite to PHP current Function. In this article, we will discuss the PHP end Function.

Syntax

end ($array)

Parameters

The function expects only one parameter. It is the array of which we want to find the last element.

Return Value

The function returns the last element of the array. Also, it sets the internal pointer to the last element. However, if the array is empty, it returns FALSE.

PHP end Function

Examples

Let’s discuss a few examples of using the function.

Example 1: Simple Usage

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	$lastElement = end($testArray);
	print_r($lastElement);
	//Banana
?>

In the above example, the function returns the last element of the input array.

Example 2: Empty Array

If the input array is empty, the function returns FALSE.

<?php

	$testArray = array();
	var_dump(end($testArray));
	//bool(false)
?>

Example 3: Internal Pointer in function

For instance, consider an example demonstrating the Internal Pointer while using the function.

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	$lastElement = end($testArray); //The Array Pointer is set to the last element
	echo $lastElement;
	//Banana 

	$currentElement = current($testArray); //Now the internal pointer points to the current element
	echo $currentElement;
	//Banana
?>
  • current: Returns the current position of the internal pointer.
  • next: Moves the internal pointer to the immediate next element to the current element of the array.
  • prev: Moves the internal pointer to the immediate previous element to the current element of the array.
  • reset: Returns the internal pointer to the first element of the array.

In the above example, the current function returns the last element because the internal pointer is set to the last element by the end function.

Conclusion

In conclusion, we discussed the PHP end Function. You can read more about it on the Official PHP Documentation. Additionally, you can learn about other PHP Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *