问题描述
PHP 琐事在这里.
如果我们像这样声明一个数组:
If we declare an array like this:
<?php $arr = [ 'foo' => 'bar', NULL => 'hello' ]; ?>
我们可以这样访问它
print $arr[NULL];
这将打印hello
.为什么这是有用的、相关的或必要的?是 PHP 错误还是功能?
This will print hello
. Why is this useful, relevant or necessary? Is it a PHP bug or a feature?
我唯一的想法是你可以用 NULL 键声明数组等于一条错误消息,向任何使用 NULL 键的人解释他们的键是空的:
My only idea was that you could declare array with the NULL key being equal to an error message to explain to anyone who uses a NULL key that their key is null:
$arr[NULL] = 'Warning you have used a null key, did you mean to?';
有人觉得这有用吗?似乎是弊大于利.
Has anyone found this useful? Seems to be something to cause more harm than good.
推荐答案
引用自 手册:
Null 将被强制转换为空字符串,即键 null 实际上将存储在"下.
有关如何转换键的其他详细信息如下:
Additional details about how keys are cast are as follows:
键可以是整数或字符串.值可以是任何类型.
此外还会发生以下键转换:
Additionally the following key casts will occur:
- 包含有效十进制整数的字符串,除非数字前面有一个 + 号,否则将被转换为整数类型.例如.钥匙8"实际上会存储在 8 下.另一方面,08"不会被强制转换,因为它不是有效的十进制整数.
- 浮点数也被转换为整数,这意味着小数部分将被截断.例如.密钥 8.7 实际上将存储在8.
- 布尔值也被转换为整数,即键 true 实际存储在 1 下,键 false 存储在 0 下.
- Null 将被转换为空字符串,即键 null 将实际存储在 "" 下.
- 数组和对象不能用作键.这样做会导致警告:非法偏移类型.
至于这是否有用或必要,这是有争议的.系统要求您使用整数或字符串键,并且您已收到有关隐式键转换的警告.
As for this being useful or necessary, this is debatable. You are asked to use integer or string keys and you have been warned about implicit key casting.
这篇关于带有 NULL 键的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!