欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2024-02-02 09:47:52
...
$fruit = "banana";   $fruits = array("apple","banana","orange");   if( in_array($fruit,$fruits) ) {       //符合条件       //如何把$fruits的"banana"改成"pear"?}


回复讨论(解决方案)

$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);