Do you name your arrays using plural or singular in PHP?

Viewed 29678

When I'm naming array-type variables, I often am confronted with a dilemma: Do I name my array using plural or singular?

For example, let's say I have an array of names: In PHP I would say: $names=array("Alice","Bobby","Charles");

However, then lets say I want to reference a name in this array. For Bobby, I'd say: $names[1]. However, this seams counter-intuitive. I'd rather call Bobby $name[1], because Bobby is only one name.

So, you can see a slight discrepancy. Are there conventions for naming arrays?

12 Answers

I use the plural form. Then I can do something like:

$name = $names[1];

Name should always convey as much information as possible in case a reader is not familiar with the type declaration. An array or collection should therefore be named in the plural.

I personally find $name[1] to be misleading, since it means "the 1st element of name" which doesn't make English sense.

I usually give it something on the end like list so it would be

nameList

Otherwise, I make it plural.

Plural.

sort(name)
sort(names)

Clearly, only plural makes sense here.

And then, here:

name[1]
names[1]

Both would make sense in this context.

Therefore, plural is the only one that makes sense when referencing the whole collection and when referencing one item from the collection.

Plural for me.

For all the reasons given above and because the agreed conventions where I work (that I contributed to creating) require plurals for arrays / lists / vectors etc.

Although plural naming can cause some anomalies in some cases the majority case is that it provides enhanced clarity and code that is easier to scan read without that annoying feeling of your mind catching on a strange construction and interrupting the flow while you go back to unsnag your brain from whatever tripped it up.

Plural although the teach you to do it singular in school so you can say:

value[0] = 42;

and really if you think about it that does make more sense than:

values[0] = 42

say it out loud if you don't believe me. Regardless I do use plurals so that I can easily tell when I am scanning through code. That also seems to be the standard that people are using these days.

What the others said: plural.

It is even more flagrant in PHP:

$name = 'Bobby';
echo $name[1];

will display o. :-)

I must admit I asked myself the same question some years ago, but showing the plural nature of the array or collection was more important than English meaning when accessing one member...

Always plural. Same for lists of any other datatype that can hold more than one element.

Always plural. That way there isn't any confusion when I do...

for each (string person in people)
{
    //code
}

I normally use the plural form, or sometimes the same way as cited up here, adding List to the name...

Related