如何在 php 中的数组中替换特定键的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8199011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:08:25  来源:igfitidea点击:

How can I replace a specific key's value in an array in php?

phparraysreplace

提问by zeckdude

I have a an array that has 3 values. After the user pushes the submit button I want it to replace the the value of a key that I specify with another value.

我有一个包含 3 个值的数组。在用户按下提交按钮后,我希望它用另一个值替换我指定的键的值。

If I have an array with the values (0 => A, 1 => B, 2 => C), and the function is run, the resulting array should be (0 => A, 1 => X, 2 => C), if for example the parameter for the function tells it to the replace the 2nd spot in the array with a new value.

如果我有一个包含 values 的数组(0 => A, 1 => B, 2 => C),并且运行该函数,则结果数组应该是(0 => A, 1 => X, 2 => C),例如,如果函数的参数告诉它用新值替换数组中的第二个点。

How can I replace a specific key's value in an array in php?

如何在 php 中的数组中替换特定键的值?

回答by Aurelio De Rosa

If you know the key, you can do:

如果您知道密钥,则可以执行以下操作:

$array[$key] = $newVal;

If you don't, you can do:

如果你不这样做,你可以这样做:

$pos = array_search($valToReplace, $array);
if ($pos !== FALSE)
{
   $array[$pos] = $newVal;
}

Note that if $valToReplace is found in $array more than once, the first matching key is returned. More about array_search.

请注意,如果在 $array 中多次找到 $valToReplace,则返回第一个匹配的键。更多关于array_search