What is an array internal pointer in PHP?

旧时模样 提交于 2019-12-05 22:53:15

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/28059372/what-is-an-array-internal-pointer-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!