Asked 7 years ago
28 Dec 2016
Views 1160

posted

unset never reset the Internal pointer in php , why ?

why Internal pointer never reset or never get minus ?

$value[]=1;
$value[]=2;
unset($value[1]);
$value[]=2;
print_r($value)//Array ( [0] => 1 [2] => 2 ) 

when we do unset($value[1]); it remove array value from index 1 but if add new value it goes to next increment internal pointer , it is 2 in our case . it means php will not reuse it next time until whole array not redefined or restart.

why it is there is no intelligent indexing are there in php . in mostly array
why unset only remove value and index but dont fill it again when next value come up to push.
rajiv

rajiv
answered Apr 24 '23 00:00

The unset function in PHP removes a variable or an element from an array, but it does not reset the internal pointer of the array. The internal pointer is a separate variable that keeps track of the current position within an array. When an element is removed from an array using unset , the remaining elements' indices are adjusted, but the internal pointer remains in the same position since it is not tied to the array indices, but the actual position of the pointer within the array.

To reset the internal pointer of an array in PHP, the reset function can be used. The reset function moves the internal pointer to the first element of the array and returns its value. Similarly, the end function can be used to move the internal pointer to the last element of the array and return its value. The next function can be used to move the internal pointer to the next element in the array and return its value.

It is important to keep in mind that when unset is used on an array element, the element may not be removed immediately. PHP's garbage collector frees the memory occupied by the removed element when it is no longer being used by the program. Therefore, resetting the internal pointer after using unset may not always be necessary
Post Answer