Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions ext/standard/array.c
Original file line number Diff line number Diff line change
Expand Up @@ -4275,15 +4275,20 @@ static zend_always_inline void php_array_merge_wrapper(INTERNAL_FUNCTION_PARAMET
ret = &args[0];
}
if (ret) {
if (HT_IS_PACKED(Z_ARRVAL_P(ret))) {
if (HT_IS_WITHOUT_HOLES(Z_ARRVAL_P(ret))) {
HashTable *ht = Z_ARRVAL_P(ret);
/* ZEND_LONG_MIN means no integer key yet, the next append uses index 0. */
zend_long next_free = ht->nNextFreeElement == ZEND_LONG_MIN ? 0 : ht->nNextFreeElement;

/* array_merge() renumbers integer keys from 0, so the next free index must match. */
if (HT_IS_PACKED(ht)) {
if (HT_IS_WITHOUT_HOLES(ht) && next_free == (zend_long) ht->nNumOfElements) {
RETURN_COPY(ret);
}
} else {
} else if (next_free == 0) {
bool copy = true;
zend_string *string_key;

ZEND_HASH_MAP_FOREACH_STR_KEY(Z_ARRVAL_P(ret), string_key) {
ZEND_HASH_MAP_FOREACH_STR_KEY(ht, string_key) {
if (!string_key) {
copy = false;
break;
Expand All @@ -4304,6 +4309,8 @@ static zend_always_inline void php_array_merge_wrapper(INTERNAL_FUNCTION_PARAMET
/* Note: If it has holes, it might get sequentialized */
if (HT_IS_WITHOUT_HOLES(src) && zend_may_modify_arg_in_place(arg)) {
dest = src;
/* array_merge() renumbers integer keys from 0, so reset a stale next free index. */
dest->nNextFreeElement = dest->nNumUsed;
in_place = true;
RETVAL_ARR(dest);
} else {
Expand Down
91 changes: 91 additions & 0 deletions ext/standard/tests/array/array_merge_empty_array_result.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
--TEST--
array_merge() with an empty argument returns an array with a fresh next free index
--FILE--
<?php
// The result must behave like a fresh array: integer keys renumbered from 0.

$a = [1, 2, 3];
unset($a[2]);
$r = array_merge($a, []);
$r[] = 4;
var_dump($r);

$b = ['a' => 1];
$b[] = 2;
unset($b[0]);
$r = array_merge([], $b);
$r[] = 3;
var_dump($r);

// A temporary array is reused in place when it is the first argument.
function holey_array() {
$a = [1, 2, 3];
unset($a[2]);
return $a;
}

$r = array_merge(holey_array(), []);
$r[] = 4;
var_dump($r);

$r = array_merge(holey_array());
$r[] = 4;
var_dump($r);

$r = array_merge(holey_array(), ['k' => 'x']);
$r[] = 4;
var_dump($r);

$r = array_merge_recursive(holey_array(), []);
$r[] = 4;
var_dump($r);
?>
--EXPECT--
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(4)
}
array(2) {
["a"]=>
int(1)
[0]=>
int(3)
}
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(4)
}
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(4)
}
array(4) {
[0]=>
int(1)
[1]=>
int(2)
["k"]=>
string(1) "x"
[2]=>
int(4)
}
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(4)
}
Loading