Home > Backend Development > PHP Tutorial > 搜索阵列一个特定值后,如何取代掉?

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

WBOY
Release: 2016-06-23 13:38:20
Original
854 people have browsed it

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


回复讨论(解决方案)

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template