Topic on Manual talk:Coding conventions

[PHP] Spaces in array indexes

5
DKinzler (WMF) (talkcontribs)

The convention currently states: Do not put spaces in brackets when accessing array elements. However, this is awkward if the index is not a literal, especially if it is an expression that contains spaces. For example:

  $a[0]
  $a['foo']
  $a[$i]
  $a[$i + 1]
  $a['x' . $name]
  $a[$this->get( $something, foo)]

We seem to already deviate from the convention in such cases, I found more than 100 places in core that use spaces in array indexes. I propose to change the convention as follows: Do not put spaces in brackets when accessing array elements if the index is a literal or variable. Do put spaces after the opening bracket and before the closing bracket if the index is an expression that by convention should contain spaces anywhere. For example:

  $a[0]
  $a['foo']
  $a[$i]
  $a[ $i + 1 ]
  $a[ 'x' . $name ]
  $a[ $this->get( $something, foo) ]

I think that is much more readable and intuitive. What do you think?

I'd personally also be fine to always add spaces in array indexes, if that is preferable for consistency.

Jdforrester (WMF) (talkcontribs)

(I've noted in the title that you're talking about Manual:Coding conventions/PHP rather than Manual:Coding conventions because the talk pages were all merged together for visibility.)

I think that we should do this, and for a little bit further and just use spaces always in square brackets; this would align our PHP convention with our JS one, which would make the rule very simple to remember.

The old excuse that this would be a lot of work is not a real problem, as we now have both auto-fixers in the linters and an auto-upgrader bot that will fix every repo for us.

Tgr (WMF) (talkcontribs)

I think the concern with changes like that was less that it's a lot of work and more that it touches a lot of lines (and so is a pain in the ass when doing git blame).


Apparently GitHub supports a default ignore-revs file these days; not sure about other tools.

Jdforrester (WMF) (talkcontribs)
Od1n (talkcontribs)

Agree about using spaces in declarations and accesses, i.e. [ 'foo', 'bar' ], $a[ 0 ], and []. Do not use different rules for declaration vs. access (or destructuring, etc.), nor for index being simple (literal or variable) or an expression.

Reply to "[PHP] Spaces in array indexes"