PHP pos Function
last modified March 13, 2025
The PHP pos function retrieves the current element in an array.
It's an alias of current and works with the internal pointer.
Basic Definition
The pos function returns the value of the current array element.
It doesn't move the pointer. Returns false if the pointer is beyond bounds.
Syntax: pos(array|object $array): mixed. Works with both arrays
and objects implementing Traversable. Returns false on empty array.
Basic pos Example
This demonstrates getting the current element from a simple array.
<?php $fruits = ['apple', 'banana', 'cherry']; $current = pos($fruits); echo "Current fruit: $current";
The pointer starts at first element. pos returns 'apple' without
changing the pointer position. Identical to current.
After Pointer Movement
Shows pos behavior after moving the array pointer.
<?php $colors = ['red', 'green', 'blue']; next($colors); // Move to second element $current = pos($colors); echo "Current color: $current";
After next moves the pointer, pos returns the
second element. The function simply reports current position without moving.
With Associative Array
Demonstrates pos working with associative arrays.
<?php
$user = [
'name' => 'John',
'age' => 32,
'email' => 'john@example.com'
];
reset($user); // Ensure pointer at start
$firstValue = pos($user);
echo "First value: $firstValue";
pos returns the value of the first element in associative arrays.
The function works the same regardless of array keys being numeric or string.
Empty Array Behavior
Shows pos return value when used with empty arrays.
<?php $empty = []; $result = pos($empty); var_dump($result);
When array is empty, pos returns false. This matches
current behavior. Always check return value with empty arrays.
After end() Function
Demonstrates pos behavior when pointer is at array end.
<?php $numbers = [10, 20, 30]; end($numbers); // Move to last element $last = pos($numbers); echo "Last number: $last";
After end moves pointer to last element, pos
returns that element's value. The pointer remains at the last position.
Best Practices
- Pointer Awareness: Know pointer position before using pos.
- Reset First: Use reset() if unsure of pointer position.
- False Check: Verify return value could be false.
- Readability: Consider current() for clearer code.
Source
This tutorial covered the PHP pos function with practical
examples showing its usage for array pointer operations.
Author
List all PHP Array Functions.