在 PHP 中,关联数组索引是否需要遵循相同的规则和变量名(不能以数字等开头)。我正在寻找这个问题的工作和哲学答案。
5 回答
从手册:
键可以是整数或字符串。如果键是整数的标准表示,它将被解释为这样(即“8”将被解释为 8,而“08”将被解释为“08”)。键中的浮点数被截断为整数。索引和关联数组类型在 PHP 中是相同的类型,既可以包含整数索引,也可以包含字符串索引。
在他们的示例中,使用类似的东西$array["08"]
是完全可以接受的,并且会被视为一个字符串,尽管您可能知道,强烈不推荐使用它。始终按逻辑命名变量。
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.
不,它们可以是任何字符串,甚至是二进制字符串。
就约定而言,通常是为了区分变量名和索引,我见过人们使用小写字母和下划线。虽然很乏味,但我发现它增加了可读性,因为眼睛期望一个通常用一个单词命名的数组的小写索引:array['array_index']
看起来不错;array['arrayIndex']
在某些代码中通常更难阅读。