Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an array internal pointer in PHP?

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?

like image 559
Chris Bier Avatar asked Jan 21 '15 03:01

Chris Bier


People also ask

What is internal pointer in array?

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']; } }

What is an array pointer in PHP?

In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array which is called as the current element of the array. Usually, the next element at the beginning is the second inserted element in the array.

What is an internal pointer?

A pointer variable keeps an address which is associated with another variable. A pointer varialbe also occupies space in memory and you can get its address as well.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


1 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?

like image 104
deceze Avatar answered Oct 16 '22 06:10

deceze