Is it within PSR-12 standard to break foreach into multiple lines
snake-py opened this issue · comments
The foreach
is not too clear whether it is okay to break the expression into multiple lines. https://www.php-fig.org/psr/psr-12/#55-foreach . Other expressions like for
and while
are very clear on the issue. I am unsure why this restriction is on foreach
if other loop expressions are "allowed" to do this.
I need to know for these two issues:
squizlabs/PHP_CodeSniffer#3673
prettier/plugin-php#2060
example:
foreach (
$client->getContractsByCustomerId($customer["id"])
as $contract
) {
or is only this within the standard:
foreach ($client->getContractsByCustomerId($customer["id"]) as $contract) {
Nether PSR-12 nor the Coding Style PER would allow splitting foreaches the way you're showing, the only allowed use of foreach is as shown in the example you linked. A more readable approach would be to use a variable to store the array you're iterating over:
$contracts = $client->getContractsByCustomerId($customer['id']);
foreach ($contracts as $contract) {
...
}
@KorvinSzanto I don't see anywhere that this is explicitly prohibited, or allowed within the PER-CS or PSR-12 language around the foreach
expressions, it is explicitly allowed for while
, if
, for
, etc, will this be clarified in a future edition of PER-CS?
I'd definitely accept a pull request, it could be written more clearly with MUSTs.
@KorvinSzanto As a contributor and user of the PHP prettier code formatter, I am trying to understand where the decision that a foreach
must be on a single line, while there is no such restriction on almost all other control structure's expressions. I would prefer to open a PR to document a 'standard' way to split a foreach
expression onto multiple lines where there is not enough room for it all to fit.