PHP current is an inbuilt function in PHP. It returns the value which the internal pointer is currently pointing to in an array. However, it does not increment or decrement the current pointer after returning the value. In this article, we will discuss the PHP current Function.
The function expects only one parameter. It is the array of which we want to find the current element.
The PHP current function returns the element which the internal pointer is currently pointing to. It is usually the first input element of the array. However, if the array is empty, it returns FALSE.
<?php $testArray = array('Apple', 'Mango', 'Banana'); $currentElement = current($testArray); print_r($currentElement); //Apple ?>
In the above example, the array consists of three elements. The current function returns the first element from the array.
<?php $testArray = array('Apple', 'Mango', 'Banana'); echo current($testArray); //Apple. The first element is Apple echo next($testArray); //Mango. The next element is Mango echo current($testArray); //Mango. Now the current element is Mango echo prev($testArray); //Apple. The previous element is Apple echo end($testArray); //Banana. The last element is Banana echo reset($testArray); //Apple. Moves the internal pointer back to the first element ?>
- 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.
- end: Moves the internal pointer to the last element of the array.
- reset: Returns the internal pointer to the first element of the array.
To traverse an array which may contain FALSE element, we should use the foreach loop instead of the current function. This is because the function returns FALSE on an empty array also. Therefore, the FALSE element and empty array are indistinguishable from a FALSE element. If you still want to use this function to traverse, use the PHP key Function to strictly check the key to be different from NULL.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.