当前位置:Gxlcms > PHP教程 > 搜索阵列一个特定值后,怎么取代掉

搜索阵列一个特定值后,怎么取代掉

时间:2021-07-01 10:21:17 帮助过:27人阅读

搜索阵列一个特定值后,如何取代掉?

$fruit = "banana";
$fruits = array("apple","banana","orange");
if( in_array($fruit,$fruits) ) {
//符合条件
//如何把$fruits的"banana"改成"pear"?
}

------解决思路----------------------
本帖最后由 xuzuning 于 2015-03-19 15:27:56 编辑

$fruit = "banana";   
$fruits = array("apple","banana","orange");
if( in_array($fruit,$fruits) ) {
$fruits[array_search($fruit, $fruits)] = "pear";
}
print_r($fruits);
Array
(
[0] => apple
[1] => pear
[2] => orange
)

对于这种需求,一般就不必先用 in_array 检查了
$fruit = "banana";   
$fruits = array("apple","banana","orange");
if(false !== ($t = array_search($fruit, $fruits)) ) {
$fruits[$t] = "pear";
}
print_r($fruits);

人气教程排行