PHP current() Function

What is PHP current() Function:

The PHP current() function returns the value of the current element where the internal pointer is pointing. Every array has an internal pointer that always points to one array element at any given time. That element is called the current element of that array which is initialized to the first element of the array.

Syntax:

current(array)

Parameters:

array: It is the array where we’ll look for the value of the current element.

Return Values:

This function returns-

  • Value of the current element – if the internal pointer pointing to an element. Check example 1.
  • FALSE – on an empty array element. Check example 2.
  • FALSE – on an element that is beyond the range. Check example 3.

Examples:

Example 1:

<?php
$varFunc = array('current function','current function');
echo current($varFunc);
?>

Output:

current function

Explanation:

The current() function by default pointing to the first element (current function) of the array.

Example 2:

<?php
$varFunc = array();
var_dump(current($varFunc));
?>

Output:

bool(false)

Explanation:

As the $varFunc array is an empty array, the current() function returns FALSE.

Example 3:

<?php
$varFunc = array('current function','current function');
current($varFunc);
prev($varFunc);
var_dump(current($varFunc));

$varFunc= array('current function','current function');
current($varFunc);
end($varFunc);
next($varFunc);
echo "<br />";
var_dump(current($varFunc));
?>

Output:

bool(false)
bool(false)

Explanation:

The current($varFunction) is setting the pointer to the first element of the array $varFunction. Then, the function prev($varFunc) is setting the pointer to the previous element of the first element which is out of the array’s range. That’s why the function current($varFunction at line 5 returns FALSE.

Similarly, the end($varFunc) function at line 9 is setting the internal pointer to the last element (current function) and the next($varFunc) function at line 10 is trying to setting the internal pointer to an element which doesn’t exist and out of range of the array. That’s why the function current($varFunction at line 12 returns FALSE.

Notes on PHP current() function:

  • This function can’t move (increment or decrement) the pointer to other element. It only informs about the value of the current element.
  • The current() function is alias of pos() function.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP mktime() Function

current() function is one of the built-in array functions in PHP. You can perform the array related tasks once you get the current array element of the element with the current() function.

Reference:

https://www.php.net/manual/en/function.current.php