Home » Php » What is an array internal pointer in PHP?

What is an array internal pointer in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am using end() to set the internal pointer of an array to its last element. Then I am using key() to get the key of that last element.

For example:

$array = ('one' => 'fish', 'two' => 'fish', 'red' => 'fish', 'blue' => 'fish');
end($array)
$last_key = key($array);

The only thing that I do not understand is what the internal pointer of an array is exactly. Can someone explain it to me? I’ve been trying but cannot find an explanation.

Also, how does setting the internal pointer of an array affect that array?

How to&Answers:

There’s an internal implementation for “arrays” in PHP “behind the scenes”, written in C. This implementation defines the details of how array data is actually stored in memory, how arrays behave, how they can be accessed etc. Part of this C implementation is an “array pointer”, which simply points to a specific index of the array. In very simplified PHP code, it’s something like this:

class Array {

    private $data = [];
    private $pointer = 0;

    public function key() {
        return $this->data[$this->pointer]['key'];
    }

}

You do not have direct access to this array pointer from PHP code, you can just modify and influence it indirectly using PHP functions like end, reset, each etc. It is necessary for making those functions work; otherwise you couldn’t iterate an array using next(), because where would it remember what the “next” entry is?