PHP
π PHP current() and pos() Functions: Getting Current Element Value
The current() function in PHP returns the value of the array element that is currently pointed to by the internal array pointer. The pos() function is an exact alias of current() and behaves identically.
-
Alias Equality:
current($array) === pos($array). Both functions return the active element value without advancing or altering the array pointer.
π οΈ Basic Usage with Indexed Arrays
When an array is declared, its internal pointer automatically targets the first element:
$fruits = ["Apple", "Pear", "Banana"];
// Default pointer points to the first element
echo current($fruits); // Outputs: Apple
echo pos($fruits); // Outputs: Apple
π Pointer Movements: Combining with next()
Navigating the array using functions like next(), prev(), or reset() changes the active pointer location that current() reads from:
$fruits = ["Apple", "Pear", "Banana"];
// Advance internal pointer by 1 position
next($fruits);
echo current($fruits); // Outputs: Pear
echo pos($fruits); // Outputs: Pear
π§© Usage with Associative Arrays & key() Integration
current() returns the element's value regardless of whether keys are numeric or strings. Combining key() and current() provides full key-value pair details for the active pointer:
$user = [
"a" => "Apple",
"b" => "Pear",
"c" => "Banana"
];
// Returns current element value regardless of key
echo current($user); // Outputs: Apple
// Display key and value pair at active pointer location
echo key($user) . " => " . current($user); // Outputs: a => Apple
π Key Rules & Behaviors
-
1. Read-Only Operations: Neither
current()norpos()moves the internal array pointer or modifies the original array structure. -
2. Invalid Pointer Output: If the internal pointer sits beyond the last element or points to an empty array,
current()returnsfalse. -
3. Manual Pointer Navigation: These functions are typically used for custom manual pointer iteration loops rather than standard
foreachloops.
π Function Summary
| Function | What It Returns | Modifies the Array? | Return Type |
|---|---|---|---|
current() |
Value of current pointer position | β No | mixed | false |
pos() |
Value of current pointer position (Alias) | β No | mixed | false |
-
π Short Summary
-
current()and its aliaspos()retrieve the element value targeted by the active array pointer. -
They do not advance or change pointer state; combine them with
next(),prev(), orreset()to traverse. -
They return
falsewhen pointing to an empty array or an out-of-bounds pointer state.
