PHP current Function | Get Current Element in Array

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.

Syntax

current ($array)

Parameters

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

Return Value

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 current Function

Example

<?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.

Related Functions

<?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.

Expert Tip

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.

Conclusion

In conclusion, we discussed the PHP current 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 *