如何删除元素并替换为数组中的另一个元素?

时间:2012-02-03 09:54:34

标签: php arrays

我需要查找并替换数组中的元素。是否有任何单一的PHP功能?

3 个答案:

答案 0 :(得分:1)

我不知道在数组中查找和替换的任何简单函数,但您总是可以执行以下操作:

$key = array_search($oldValue, $myArray);
if ($key) $myArray[$key] = $newValue;

答案 1 :(得分:0)

您只需使用array_splice

参见示例

$input = array("red", "green", "blue", "yellow");
array_splice($input, -2, 1, array("orange", "maroon"));
// $input is now array("red", "green", "orange", "maroon","yellow")

答案 2 :(得分:0)

试试这个:

<?php
$myArray = array("John","William","Henry","Tom","Peter");
$newArray = array_splice($myArray, 2, 1, "Susan");
foreach($myArray as $key => $value) {
    echo "$key - $value <br />";
}
?>