Skip to content

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

Open
lazerg wants to merge 1 commit into
php:PHP-8.4from
lazerg:fix/gh-23576-array-keys-empty
Open

Fix GH-23576: array_keys() on an empty array returns a non-zero next index#23577
lazerg wants to merge 1 commit 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 ?

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.

2 participants