我在PHP中有一个看起来像这样的数组:
$test = array('3' => 5);
如何更换弦乐数组键3? 我试过了:
$test['3'] = "New value"
但它不起作用,之后看起来像那样:
array('3' => 5, 3 => "New value")
PHP版本:5.2.11
答案 0 :(得分:4)
非常适合我
$ php -r '$foo = array("3" => 5); $foo["3"] = 6; print_r($foo);'
Array
(
[3] => 6
)
答案 1 :(得分:2)
获取由字符串表示的数字索引的最可能方法是将具有数字属性名称的对象转换为数组。
更详细的内容涵盖here
答案 2 :(得分:2)
第一个实际上是创建一个数字索引的数组键,第二个是字符串键。您可以使用type casting强制执行一致的行为。
$test = array((string) '3' => 5);
$test[(string) '3'] = "New value";
更新,这些在PHP版本5.2.13上的行为完全相同:
$test = array('3' => 5);
echo '<pre>'.print_r($test,true).'</pre>';
$test['3'] = "New value";
echo '<pre>'.print_r($test,true).'</pre>';
$test = array((string) '3' => 5);
echo '<pre>'.print_r($test,true).'</pre>';
$test[(string) '3'] = "New value";
echo '<pre>'.print_r($test,true).'</pre>';