per-coding-style icon indicating copy to clipboard operation
per-coding-style copied to clipboard

Destructuring syntax (list() and [])

Open j-willette opened this issue 5 months ago • 7 comments

I want to report a case that does not seem to be explicitly covered by PSR-12. It concerns variable destructuring using the list() and [] syntaxes.

I have this code:

[$val1,$val2] = explode(',', $string);
list($val1,$val2) = explode(',', $string);

And I do not get any error when running the command:

phpcs --standard=PSR12 my-file.php

In my opinion, there should be a space required after the comma following $val1, as in function calls or arrays.

Correction:

[$val1, $val2] = explode(',', $string);
list($val1, $val2) = explode(',', $string);

j-willette avatar Jul 01 '25 08:07 j-willette

I'm pretty sure a space is required after any comma. Sounds like something you should take up with php-cs.

Crell avatar Jul 01 '25 14:07 Crell

PHPCS does exactly what is expected: follow PSR12. PSR12 has no rules about array or list formatting, so PHPCS doesn't enforce any.

And even PER in the current master has no rules about list formatting and has no explicit rule about spacing after a comma for arrays (other than single-line, multi-line).

jrfnl avatar Jul 01 '25 14:07 jrfnl

Surely, it would make sense to have spaces, since 4.7 says:

In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.

Arguably, these are not function calls, it's arrays and language constructs, so we may need an amendment to explicitly say that the same rule applies there too.

Jean85 avatar Jul 01 '25 15:07 Jean85

While we don't have specific cases for destructuring, it stands to reason that language constructs like list(...) = would follow the function call rules and [...] = would follow the array declaration rules.

Easy enough to add clarification in a future version but to me there isn't really much ambiguity here and we all know exactly the syntax that would be codified.

KorvinSzanto avatar Jul 01 '25 15:07 KorvinSzanto

Since we're about to tag 3.0, if we want to clarify this further, it sounds like a reasonable 3.1 target.

Crell avatar Jul 01 '25 15:07 Crell

Happy to see this addressed/made explicit in PER 3.1.

jrfnl avatar Jul 01 '25 15:07 jrfnl

but to me there isn't really much ambiguity here and we all know exactly the syntax that would be codified.

Agreed, but tools like PHPCS also need to be aware of it.

Similarly, this code doesn't raise any PHPCS error:

$array = ['val1','val2','val3'];

j-willette avatar Jul 02 '25 09:07 j-willette