Array Name: Singular or Plural?

When it comes to Arrays in PHP, which style do you use…

1.) Singular

$answer();
$name();

2.) Plural

$answers();
$names();

3.) Append “List”


$answerList();
$nameList();

4.) Append “Array”


$answerArray();
$nameArray();

I sorta like #3 or #4

Debbie

Semantically, appending list or plural makes most sense.

However I personally don’t use any plural because I hate having to double check spellings and trying to remember if i made a certain variable/reference plural or singular. Then again I’m not a purist so it’s acceptable to me, to someone who is, they might expect it to be semantically correct.

That’s how I do it. It’s unambiguous. You and anyone else who reads the code knows right away that it is an array.

I would write it like $aAnswers, where the first a stands for array :slight_smile:
My colleagues do the same thing. For us its clear. But don’t know if other people will read the a as array.

I probably use “2.) Plural” most often. So long as the names are clearly describing the contents, it’s fine whatever you pick. I’ve never been a big fan of putting the type of the value into the variable name (whether $peopleArray, or hungarian notation).

Hi,

I use plurals

$names = array();

$colours = array(‘white’ => ‘#FFFFFF’, ‘black’ => ‘#000000’, ‘light-gray’ => ‘#dddddd’);

$Regards = [‘first_name’ => ‘Steve’, ‘last_name’ = ‘Browning’];

I use plurals for arrays because there is more than one and makes the following line more readable.



  foreach( $items as $id => $item ):

     $echo $id . ' ==> ' . $item . '<br />';

  endforeach;


:tup: for @John_Betong; 's answer because this way of doing a foreach loop is much easier to read and understand the array from the value and key.

I like the style of plural for these types of variables

Yep, plurals here too.

Yes, plurals here as well. For the same “plurals to singular” reasons as stated above. Makes the code read like its a short sentence.


foreach($kittens as $kitten){

   if($kitten->isHungry())
      feed($kitten);

}