一个数字字符串作为PHP中的数组键 [英] A numeric string as array key in PHP

查看:64
本文介绍了一个数字字符串作为PHP中的数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将像"123"这样的数字字符串用作PHP数组中的键,而不必将其转换为整数?

Is it possible to use a numeric string like "123" as a key in a PHP array, without it being converted to an integer?

$blah = array('123' => 1);
var_dump($blah);

打印

array(1) {
  [123]=>
  int(1)
}

我想要

array(1) {
  ["123"]=>
  int(1)
}

推荐答案

否;不,不是:

手册:

键可以是整数或字符串.如果键是整数的标准表示形式,它将被解释为整数(即​​"8"将被解释为8,而"08"将被解释为"08").

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 (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").

附录

由于下面的注释,我认为指出该行为与JavaScript对象键相似而不是相同会很有趣.

Because of the comments below, I thought it would be fun to point out that the behaviour is similar but not identical to JavaScript object keys.

foo = { '10' : 'bar' };

foo['10']; // "bar"
foo[10]; // "bar"
foo[012]; // "bar"
foo['012']; // undefined!

这篇关于一个数字字符串作为PHP中的数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆