|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2006-02-14 17:33 UTC] tomas_matousek at hotmail dot com
Description:
------------
Operator $a[] doesn't add a correct key to the array if applied after popping from array. It seems array_pop merely checks whether the removed index is the max. int key remembered by the array and if yes it decreases it by 1. I would expect array_pop to find the new maximal key in the resulting array.
Reproduce code:
---------------
$a = array("a","b",100 => "c",200 => "d");
array_pop($a);
array_pop($a);
$a[] = "new";
var_dump($a);
Expected result:
----------------
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(3) "new"
}
Actual result:
--------------
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[199]=>
string(3) "new"
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 13:00:01 2025 UTC |
--- php-5.2.5/ext/standard/array.c 2007-11-06 11:28:21.000000000 -0200 +++ /usr/local/src/php-5.2.5/ext/standard/array.c 2008-01-28 06:35:34.000000000 -0200 @@ -1994,7 +1994,7 @@ **val; /* Value to be popped */ char *key = NULL; int key_len = 0; - ulong index; + ulong index, new_index = 0; /* Get the arguments and do error-checking */ if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &stack) == FAILURE) { @@ -2048,6 +2048,10 @@ } } else if (!key_len && index >= Z_ARRVAL_PP(stack)->nNextFreeElement-1) { Z_ARRVAL_PP(stack)->nNextFreeElement = Z_ARRVAL_PP(stack)->nNextFreeElement - 1; + } else if (!key_len && index < Z_ARRVAL_PP(stack)->nNextFreeElement-1) { + zend_hash_internal_pointer_end(Z_ARRVAL_PP(stack)); + zend_hash_get_current_key_ex(Z_ARRVAL_PP(stack), &key, &key_len, &new_index, 0, NULL); + Z_ARRVAL_PP(stack)->nNextFreeElement = new_index + 1; } zend_hash_internal_pointer_reset(Z_ARRVAL_PP(stack));This is expected behavior. Workaround you "could" do is: <?php $array = array('a', 'b', 'c', 200 => 'd'); array_pop($array); array_pop($array); $new = $array; $new[] = 'd'; $array[] = 'd'; var_dump($new); var_dump($array); ?> That way you'll have your 1,2,3 keys in $new and the correctly indexed array in $array. "Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: .." (You can see this link at: http://ie.php.net/types.array)