[php-src] master: Fix GH-23576: array_keys() on an empty array returns a non-zero next index (#23577)
| From: | Lazizbek Ergashev via Weilin Du | Date: | Mon, 07 Sep 2026 06:06:20 +0000 |
| Subject: | [php-src] master: Fix GH-23576: array_keys() on an empty array returns a non-zero next index (#23577) | ||
| Groups: | php.cvs | ||
| Request: | Send a blank email to php-cvs+get-141105@lists.php.net to get a copy of this message | ||
Author: Lazizbek Ergashev (lazerg)
Committer: Weilin Du (LamentXU123)
Date: 2026-09-07T13:28:55+08:00
Commit: https://github.com/php/php-src/commit/436589608487f9949aef8de234872a242cd8c81b
Raw diff: https://github.com/php/php-src/commit/436589608487f9949aef8de234872a242cd8c81b.diff
Fix GH-23576: array_keys() on an empty array returns a non-zero next index (#23577)
array_keys() reused the input array when it was empty. For an array
that was previously populated, this preserved the next free index and
caused later appends to start at a non-zero key, even though
array_keys() returns a list.
Return a fresh empty array, matching array_values(), and cover both
previously populated and fresh empty arrays across all argument forms.
Closes #23577
Changed paths:
A ext/standard/tests/array/gh23576.phpt
M NEWS
M ext/standard/array.c
Diff:
diff --git a/NEWS b/NEWS
index 8b5604d857ac..a8d2c0727beb 100644
--- a/NEWS
+++ b/NEWS
@@ -114,6 +114,8 @@ PHP NEWS
(arshidkv12)
. Fixed GH-23338 (fsockopen()/pfsockopen() ValueError reported wrong
argument number for $timeout). (lacatoire)
+ . Fixed bug GH-23576 (Next index for array returned from array_keys() is
+ wrong). (Lazizbek Ergashev)
- SimpleXML:
. Fixed writing to a dimension of the object returned by attributes() not
diff --git a/ext/standard/array.c b/ext/standard/array.c
index 556f9a7ee666..ebd114844ab9 100644
--- a/ext/standard/array.c
+++ b/ext/standard/array.c
@@ -4504,7 +4504,7 @@ PHP_FUNCTION(array_keys)
/* Base case: empty input */
if (!elem_count) {
- RETURN_COPY(input);
+ RETURN_EMPTY_ARRAY();
}
/* Initialize return array */
diff --git a/ext/standard/tests/array/gh23576.phpt b/ext/standard/tests/array/gh23576.phpt
new file mode 100644
index 000000000000..c3ada5559a23
--- /dev/null
+++ b/ext/standard/tests/array/gh23576.phpt
@@ -0,0 +1,58 @@
+--TEST--
+GH-23576 (Next index for array returned from array_keys() is wrong)
+--FILE--
+<?php
+$a = [123 => 123];
+unset($a[123]);
+
+$b = array_keys($a);
+$b[] = 42;
+var_dump($b);
+
+$c = array_keys($a, 123);
+$c[] = 42;
+var_dump($c);
+
+$d = array_keys($a, 123, true);
+$d[] = 42;
+var_dump($d);
+
+$e = [];
+
+$f = array_keys($e);
+$f[] = 42;
+var_dump($f);
+
+$g = array_keys($e, 123);
+$g[] = 42;
+var_dump($g);
+
+$h = array_keys($e, 123, true);
+$h[] = 42;
+var_dump($h);
+?>
+--EXPECT--
+array(1) {
+ [0]=>
+ int(42)
+}
+array(1) {
+ [0]=>
+ int(42)
+}
+array(1) {
+ [0]=>
+ int(42)
+}
+array(1) {
+ [0]=>
+ int(42)
+}
+array(1) {
+ [0]=>
+ int(42)
+}
+array(1) {
+ [0]=>
+ int(42)
+}