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

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

WBOY
Release: 2016-06-13 12:16:43
Original
830 people have browsed it

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

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

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

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

Related labels:
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