Skip to content

Fix GH-23576: array_keys() on an empty array returns a non-zero next index - #23577

Closed
lazerg wants to merge 2 commits into
php:PHP-8.4from
lazerg:fix/gh-23576-array-keys-empty
Closed

Fix GH-23576: array_keys() on an empty array returns a non-zero next index#23577
lazerg wants to merge 2 commits into
php:PHP-8.4from
lazerg:fix/gh-23576-array-keys-empty

Conversation

@lazerg

@lazerg lazerg commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

array_keys() returns the input array itself when that array is empty. An array that has held elements keeps its next free index, so array_keys() on an empty-but-previously-populated array hands back a next index that is not 0, and the first append lands on the old index instead:

$a = [123 => 123];
unset($a[123]);
$b = array_keys($a);
$b[] = 42;      // ends up at key 124, not 0

The shortcut has been there since 7.2, but it only became visible in 7.3.17 / 7.4.5, when the fix for bug #79364 made copying an empty array preserve the next free index. array_keys() is documented to return a list, so returning the caller's array is wrong regardless of what the copy preserves. Return a fresh empty array instead, which is what array_values() right below already does for the same case.

Fixes GH-23576

GH-23576 (Next index for array returned from array_keys() is wrong)
--FILE--
<?php
$a = [123 => 123];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would be nice to also test an empty array ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, thanks. Added in 457a21e. The test now also runs all three array_keys() forms on an empty array.

@LamentXU123

Copy link
Copy Markdown
Member

@devnexen Can I merge this? This looks good and I want to make this fix in before we tag out beta3 :)

@devnexen

devnexen commented Sep 7, 2026

Copy link
Copy Markdown
Member

yes go ahead

LamentXU123 added a commit that referenced this pull request Sep 7, 2026
* PHP-8.5:
  Fix GH-23576: array_keys() on an empty array returns a non-zero next index (#23577)
pull Bot pushed a commit to edisplay/php-src that referenced this pull request Sep 7, 2026
* PHP-8.4:
  Fix phpGH-23576: array_keys() on an empty array returns a non-zero next index (php#23577)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants