Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: How to Structure Arrays - Standards and Naming Conventions [closed]

What is the best practice in multidimensional array structure in terms of what elements hold the iterator vs the detail elements?

The majority of my programming experience (and I do mainly do it for fun) comes from following tutorials on google, so I apologize in advance if this seems an exceptionally daft question - but I do want to start improving my code.

Whenever I have needed to make a multidimensional array, my naming has always placed the counter in the first element.

For example, if I have a single dimensional array as follows:

$myArray['year']=2012;
$myArray['month']='July';
$myArray['measure']=3;
// and so on.

However, if I wanted to make that same array keep a few owners of history I would add another dimension and format it as follows:

$myArray[$owner]['year']=2012;
$myArray[$owner]['month']='July';
$myArray[$owner]['measure']=3;

Edit: To make sure that my example isn't off-putting or leading in the right direction, I am basically following this structure:

$myArray[rowOfData][columnOfData]

Now, my question is about accepted convention. Should I instead be doing the following?

$myArray['year'][$owner]=2012;
$myArray['month'][$owner]='July';
$myArray['measure'][$owner]=3;

Edit: using that edit from above, should it be:

$myArray[columnOfData][rowOfData]

I have searched about array naming conventions, but keep hitting articles arguing about whether to name arrays as plurals or not. The way I have been naming them seems to be more logical and I think it follows a structure that resembles an object better i.e. object->secondaryLevel->detail but for all I know I have been doing it ass-about all this time. As I getting more and more into programming, I would prefer to change my habits if they are wrong.

Is there an accepted standard or is it just anything goes with arrays? If you were looking at code written by someone else, what format would be expecting? I get that any structure that makes sense/is intuitive is accepted.

Also from an iteration point of view, which one of the following is more intuitive?:

for($i=0;$i<$someNumber;$i++)
{
    echo $myArray[$i]['year'];
    // OR
    echo $myArray['year'][$owner];
}

Edit: I did have this post tagged as c# and Java because I wanted to get some opinions outside of just PHP programmers. I think that as arrays are used in so many different languages, it would have been good to get some input from programmers in various langauges.

like image 978
Fluffeh Avatar asked Jul 18 '12 00:07

Fluffeh


People also ask

What are naming conventions in programming?

In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation.

Which of the following is the correct naming convention in C?

File Naming ConventionsThe first character of the name should be a letter and all characters (except the period) should be lower-case letters and numbers. The base name should be eight or fewer characters and the suffix should be three or fewer characters (four, if you include the period).

What is naming conventions in C language?

Naming Conventions rules for Variables and Methods (Functions) are: It should begin with an alphabet. There may be more than one alphabet, but without any spaces between them. Digits may be used but only after alphabet. No special symbol can be used except the underscore (_) symbol.

What is variable naming convention?

A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".


1 Answers

Your question is subjective, in that everyone may have a different approach to the situation you stated, and you are wise to even ask the question; How best to name your variables, classes, etc. Sad to say, I spend more time than I care to admit determining the best variable names that make sense and satisfy the requirements. My ultimate goal is to write code which is 'self documenting'. By writing self-documenting code you will find that it is much easier to add features or fix defects as they arise.

Over the years I have come to find that these practices work best for me:

Arrays: Always plural

I do this so loop control structures make more semantic sense, and are easier to work with.

// With a plural array it's easy to access a single element
foreach ($students as $student) {}

// Makes more sense semantically
do {} (while (count($students) > 0);

Arrays of objects > deep multi-dimensional arrays

In your example your arrays started blowing up to be 3 element deep multi-dimensional arrays, and as correct as Robbie's code snippet is, it demonstrates the complexity it takes to iterate over multi-dimensional arrays. Instead, I would suggest creating objects, which can be added to an array. Note that the following code is demonstrative only, I always use accessors.

class Owner
{
    public $year;
    public $measure;
    public $month;
}

// Demonstrative hydration 
for ($i = 1 ; $i <= 3 ; $i++) {

    $owner = new Owner();

    $owner->year = 2012;
    $owner->measure = $i;
    $owner->month = rand(1,12);

    $owners[] = $owner;
}

Now, you only need to iterate over a flat array to gain access to the data you need:

foreach ($owners as $owner) {
    var_dump(sprintf('%d.%d: %d', $owner->month, $owner->year, $owner->measure));
}

The cool thing about this array of objects approach is how easy it will be to add enhancements, what if you want to add an owner name? No problem, simply add the member variable to your class and modify your hydration a bit:

class Owner
{
    public $year;
    public $measure;
    public $month;
    public $name;
}

$names = array('Lars', 'James', 'Kirk', 'Robert');

// Demonstrative hydration 
for ($i = 1 ; $i <= 3 ; $i++) {

    $owner = new Owner();

    $owner->year = 2012;
    $owner->measure = $i;
    $owner->month = rand(1,12);
    $owner->name = array_rand($names);

    $owners[] = $owner;
}

foreach ($owners as $owner) {
    var_dump(sprintf('%s: %d.%d: %d', $owner->name, $owner->month, $owner->year, $owner->measure));
}

You have to remember that the above code snippets are just suggestions, if you rather stick with deep multi-dimensional arrays, then you will have to figure out an element ordering arrangement that makes sense to YOU and those you work with, if you think you will have trouble with the setup six months down the road, then it is best to implement a better strategy while you have the chance.

like image 78
Mike Purcell Avatar answered Sep 23 '22 13:09

Mike Purcell