What is PHP pos() function?
The PHP pos() function returns the value of the current element of an array 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:
pos(array)
Parameter:
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('pos function','current function');
echo pos($varFunc);
?>
Output:
pos function
Explanation:
The pos() function by default pointing to the first element (pos function) of the array.
Example 2:
<?php
$varFunc = array();
var_dump(pos($varFunc));
?>
Output:
bool(false)
Explanation:
As the $varFunc array is an empty array, the pos() function returns FALSE.
Example 3:
<?php
$varFunc = array('pos function','current function');
pos($varFunc);
prev($varFunc);
var_dump(pos($varFunc));
$varFunc= array('pos function','current function');
pos($varFunc);
end($varFunc);
next($varFunc);
echo "<br />";
var_dump(pos($varFunc));
?>
Output:
bool(false)
bool(false)
Explanation:
The pos($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 pos($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 pos($varFunction at line 12 returns FALSE.
Notes on PHP pos() 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 pos() function is alias of current() function.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP pos() Function
PHP pos() function is useful built-in array function to get the current element of the array and then perform the other necessary operations based on it.