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:

PHP
$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:

PHP
$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:

PHP
$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() nor pos() 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() returns false.
  • 3. Manual Pointer Navigation: These functions are typically used for custom manual pointer iteration loops rather than standard foreach loops.

πŸ“Š 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 alias pos() retrieve the element value targeted by the active array pointer.
  • They do not advance or change pointer state; combine them with next(), prev(), or reset() to traverse.
  • They return false when pointing to an empty array or an out-of-bounds pointer state.