Current Location: Home> Latest Articles> Use PHP current() to read the current value of the associative array

Use PHP current() to read the current value of the associative array

gitbox 2025-05-29

Example: Use current() to read the current value of the associative array

 <?php
$fruits = [
    "a" => "apple",
    "b" => "banana",
    "c" => "cherry"
];

// The default pointer points to the first element
echo current($fruits);  // Output apple

// Move the pointer to the next element
next($fruits);
echo current($fruits);  // Output banana

// Move the pointer again
next($fruits);
echo current($fruits);  // Output cherry

// If called again next,Pointer out of range
next($fruits);
var_dump(current($fruits));  // Output bool(false)
?>

In this example, current() reads the element value pointed to by the associative array $fruits pointer.


Combining the use of reset() and key() functions

Generally, when reading an array, using reset() in conjunction with the process of repositioning the pointer to the beginning of the array, ensuring that it is read from scratch, and key() can get the key name of the current element.

 <?php
$users = [
    "id1" => "Alice",
    "id2" => "Bob",
    "id3" => "Charlie"
];

reset($users);           // Reset pointer to first element
echo key($users) . ": " . current($users) . "\n";  // Output id1: Alice

next($users);
echo key($users) . ": " . current($users) . "\n";  // Output id2: Bob
?>

This way you can clearly know the keys and values ​​that the current pointer points to.


Practical application scenarios

  • During the process of traversing the array, the current value needs to be read multiple times without changing the pointer.

  • Combining next() and prev() to implement custom array traversal logic.

  • When processing an associative array, use current() to quickly read the value of the current position.


Summarize

  • current() is used to get the value of the element pointed to by the current pointer of the array.

  • The position of the pointer will not be changed.

  • It can be used with reset() , next() , key() and other functions to flexibly manipulate array pointers.

  • It also works perfectly for associative arrays.

With the use of current() , you can operate PHP arrays more efficiently.