Strange php array pointer

$a=array('a','b','c','d');

while(key($a)!==NULL){
  echo key($a).'=>'.current($a).'<br/>';
  next ($a);
}

prev($a);
var_dump(current($a));

Why var_dumpreturns falseinstead "d"?

+5
source share
2 answers

This is definitely by design, and although I combed through the PHP documentation, I can’t find a link to the fact that as soon as you cancel the pointer by nextpast the end of the array, you can no longer use it prev, the PHP ( zend_hash.c) source code makes it clear what happens:

ZEND_API int zend_hash_move_forward_ex(HashTable *ht, HashPosition *pos)
{
    HashPosition *current = pos ? pos : &ht->pInternalPointer;

    IS_CONSISTENT(ht);

    if (*current) {
        *current = (*current)->pListNext;
        return SUCCESS;
    } else
        return FAILURE;
}

ZEND_API int zend_hash_move_backwards_ex(HashTable *ht, HashPosition *pos)
{
    HashPosition *current = pos ? pos : &ht->pInternalPointer;

    IS_CONSISTENT(ht);

    if (*current) {
        *current = (*current)->pListLast;
        return SUCCESS;
    } else
        return FAILURE;
}

As you can see, zend_hash_move_backwards_ex(which maps to in PHP prev) checks if the current pointer is valid before doing anything, and zend_hash_move_forward_exsets the value pListNextthat will be nullin the case of the last element.

. , next prev C, , NULL, .

, , . , end , , .

( end()), , . ( , , prev() )

( : PHP inconsistent C-: zend_hash_move_forward_ex vs zend_hash_move_backward*s*_ex.)

+4
$a=array('a','b','c','d');

while(key($a)!==NULL){
  echo key($a).'=>'.current($a).'<br/>';
  next ($a);
}

prev($a);
var_dump(current($a));

, , , .. null. var_dump(current($a)); retunrs false

$a=array('a','b','c','d');

while(key($a)!==NULL){
  echo key($a).'=>'.current($a).'<br/>';
  next ($a);
}

//prev($a);
end(($a);
var_dump(current($a));

d, d

0

All Articles