8

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.

2
  • no. most do start with a number $foo=array('x','y'); indexes are 0 and 1 Commented Aug 16, 2011 at 20:47
  • @Dagon we are discussing associative arrays. Commented Aug 16, 2011 at 20:57

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I just thought I would add that the string can contain spaces even though none of the examples do.
For strictly practical reasons I think you should choose such index names which are "selectable with double clicks" in code editors, like: array['array_key']. A bad example: array['key@array'].
2

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.

Comments

2

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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.