user897363
user897363

Reputation: 81

php - associative array index naming conventions

In PHP, do associative array indexes need to follow that same rules and variable names (can't start with a number, etc.) I am looking for both working and philosophical answers to this question.

Upvotes: 8

Views: 7535

Answers (5)

djhaskin987
djhaskin987

Reputation: 10107

as far as convention goes, often to differentiate between variable names and indexes I've seen people use lowercase letters and underscores. Although tedious, I find it increases readability because the eye expects a small-case index for an array named usually with one word: array['array_index'] looks good; array['arrayIndex'] is often harder to read in some code.

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 175098

From the manual:

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

In their example, using something like $array["08"] is perfectly acceptable and will count as a string, though as you ptobably know, it's highly not recommended. Always name your variables logically.

Upvotes: 6

Alex Howansky
Alex Howansky

Reputation: 53646

No, they can be any string, even a binary one.

Upvotes: 0

GSto
GSto

Reputation: 42380

no, associative arrays can have numerical keys. any valid string can be an index. as far as code styles and clarity, the important thing is that is the keys make sense and are readable.

Upvotes: 2

George Cummins
George Cummins

Reputation: 28936

An array key can be an integer or any valid string, according to the manual.

From a philosophical standpoint, the key should make sense in context and add to the readability of the code.

Upvotes: 1

Related Questions