将空字符串保存为数组键是否可以?

时间:2016-01-12 07:58:35

标签: php arrays key

我想知道如果我们将一个空字符串作为数组键保存就好了,就像这个

一样
$test = array (
  '' => 'Select',
  1 => 'Internal',
  2 => 'External'
);

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:4)

数组键应该是整数或字符串 将空字符串作为数组键处理远非理想的做法 此外 Null 将被转换为空字符串,即键null实际上将存储在“”下。
但是这样的方法会使你的阵列模糊不清 请考虑以下示例:

Artisan::output()

下一个案例出现歧义:

$test = array (
  '' => 'Select',
  1 => 'Internal',
  2 => 'External',
  '' => 'select'
);

var_dump(array_key_exists('', $test));   // output 'bool(true)', not so bad - but only at first glance

,最后一个例子出现错误(通知):

var_dump($test[""]);   // output "select"

答案 1 :(得分:1)

这样做会很好但不是很好的方法。例如,如果需要检查数组的null键,则此空字符串将返回true。这种方法会在其他严格类型的语言(如java和C)中产生语法错误。 因此,最好避免这种编码:)