简体   繁体   English

php - 关联数组索引命名约定

[英]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.在 PHP 中,关联数组索引是否需要遵循相同的规则和变量名(不能以数字等开头)。我正在寻找这个问题的工作和哲学答案。

From the manual :手册

A key may be either an integer or a string.密钥可以是 integer 或字符串。 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").如果键是 integer 的标准表示,它将被解释为这样(即“8”将被解释为 8,而“08”将被解释为“08”)。 Floats in key are truncated to integer.键中的浮点数被截断为 integer。 The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.索引和关联数组类型在 PHP 中是相同的类型,它们都可以包含 integer 和字符串索引。

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.在他们的示例中,使用类似$array["08"]的东西是完全可以接受的,并且会被视为一个字符串,尽管您可能知道,强烈不建议这样做。 Always name your variables logically.始终按逻辑命名变量。

no, associative arrays can have numerical keys.不,关联 arrays 可以有数字键。 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.就代码 styles 和清晰度而言,重要的是密钥有意义且可读。

An array key can be an integer or any valid string, according to the manual .根据手册,数组键可以是 integer 或任何有效字符串。

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['array_index']看起来不错; array['arrayIndex'] is often harder to read in some code. array['arrayIndex']在某些代码中通常更难阅读。

PHP manual : PHP 手册

The key can either be an int or a string.键可以是 int 或字符串。 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 .但请注意,在 PHP 的世界中,有一种常见的技术是使用extract将数组条目转换为变量。 So, I think it is better to be opinionated and follow variables_naming_convention .所以,我认为最好是固执己见并遵循variables_naming_convention

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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