简体   繁体   中英

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.

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 (ie "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.

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.

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.

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

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.

PHP manual :

The key can either be an int or a string. The value can be of any type.

And there are some auto-casting cases for numerical keys.

But note that in the world of PHP, there is a common technique of turning array entries into variables using extract . So, I think it is better to be opinionated and follow variables_naming_convention .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM