Skip to content

Fix integer key renumbering in constant array unpacking - #1174

Merged
nikic merged 1 commit into
nikic:masterfrom
ydah:fix-array-unpack-keys
Oct 5, 2026
Merged

nikic merged 1 commit into
nikic:masterfrom
ydah:fix-array-unpack-keys

Conversation

@ydah

@ydah ydah commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

ConstExprEvaluator uses array_merge() for array unpacking, which renumbers existing integer keys:

$expr = $parser->parse('<?php [5 => "a", ...[1, 2]];')[0]->expr;
$evaluator->evaluateDirectly($expr);
// Before: [0 => "a", 1 => 1, 2 => 2]
// After:  [5 => "a", 6 => 1, 7 => 2]

Append unpacked integer-keyed values and assign string-keyed values directly, preserving existing keys and matching PHP's behavior. Even an empty unpack ([5 => "a", ...[]]) now preserves key 5.

Comment thread lib/PhpParser/ConstExprEvaluator.php Outdated
$array = array_merge($array, $this->evaluate($item->value));
$unpacked = $this->evaluate($item->value);
if (!is_array($unpacked)) {
throw new \TypeError('Unpacked value must be an array');

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Suggested change
throw new \TypeError('Unpacked value must be an array');
throw new \Error('Only arrays can be unpacked in constant expression');

To match the error produced by PHP, based on: https://github.com/php/php-src/blob/f73ab1c244adf57058279adb72d7b6bf40d09a96/Zend/zend_ast.c#L637.

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.

Thank you. Updated the exception to \Error with the matching message, and adjusted the test to check the message as well.

@ydah
ydah force-pushed the fix-array-unpack-keys branch from 1e3c062 to a7c1415 Compare October 5, 2026 06:11
@ydah
ydah requested a review from nikic October 5, 2026 06:12
@nikic
nikic merged commit 35c417e into nikic:master Oct 5, 2026
12 checks passed
@ydah
ydah deleted the fix-array-unpack-keys branch October 5, 2026 07:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants