Making arrays more readable

Formatting code to make it more readable for other humans is a very important concept in computer programming. There are many techniques that we can use to make code more readable and one involves arrays and array keys. Have a look at the code below and think about how readable it is.

while ($row = mysql_fetch_assoc($result)) { $rows[$row['type']][$row['name']] = $row['result']; }

Lots of keys laid out on a tableBy placing array values from array keys within a key segment of an array can be quite confusing because of the multiple brackets that occur. Even explaining the situation can be confusing. What we need to do is figure out a better way to write our scripts. This may involve creating more lines of code, but if the code becomes more readable, this is the best solution. Below is a revised array code.

while ($row = mysql_fetch_assoc($result)) { $type = $row['type']; $name = $row['name']; $rows[$type][$name] = $row['result']; }

The code is now more readable. We can see the last line is creating a multi dimensional array with a type as the first key and the name as the second key. The key to writing more readable code is not to produce code in as few lines as possible, but to have as few lines of succinct readable code as possible.