I have an array in PHP which looks like that:
我在PHP中有一个数组,看起来像这样:
$test = array('3' => 5);
How could I replace the stringed array key 3? I tried:
我怎么能更换弦乐数组键3?我试过了:
$test['3'] = "New value"
but it don't work, it look like that after that:
但它不起作用,之后看起来像那样:
array('3' => 5, 3 => "New value")
PHP version: 5.2.11
PHP版本:5.2.11
3 个解决方案
#1
2
The most possible way you can get the numerical index represented by string is when you convert object with numeric property name to array.
获取由字符串表示的数字索引的最可能方法是将具有数字属性名称的对象转换为数组。
More detailed this covered here
这里介绍的更详细
#2
4
Works great for me
对我很有用
$ php -r '$foo = array("3" => 5); $foo["3"] = 6; print_r($foo);'
Array
(
[3] => 6
)
#3
2
The first is actually creating a numerically indexed array key, the second a string key. You can use type casting to force consistent behavior.
第一个实际上是创建一个数字索引的数组键,第二个是字符串键。您可以使用类型转换来强制执行一致的行为。
$test = array((string) '3' => 5);
$test[(string) '3'] = "New value";
Update, these behave identically for me on PHP Version 5.2.13:
更新,这些在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>';
#1
2
The most possible way you can get the numerical index represented by string is when you convert object with numeric property name to array.
获取由字符串表示的数字索引的最可能方法是将具有数字属性名称的对象转换为数组。
More detailed this covered here
这里介绍的更详细
#2
4
Works great for me
对我很有用
$ php -r '$foo = array("3" => 5); $foo["3"] = 6; print_r($foo);'
Array
(
[3] => 6
)
#3
2
The first is actually creating a numerically indexed array key, the second a string key. You can use type casting to force consistent behavior.
第一个实际上是创建一个数字索引的数组键,第二个是字符串键。您可以使用类型转换来强制执行一致的行为。
$test = array((string) '3' => 5);
$test[(string) '3'] = "New value";
Update, these behave identically for me on PHP Version 5.2.13:
更新,这些在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>';