Home >Backend Development >PHP Tutorial >How to check the value in an array with PHP function in_array()_PHP Tutorial
While studyingThe following example program will display the string "Not found in this array" on the page. Because the string "Albert" you are looking for is indeed not in the $namesArray array:
The following is the specific use of the PHP function in_array()
<ol class="dp-xml"> <li class="alt"><span><span><? $</span><span class="attribute"><font color="#ff0000">namesArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array</font></span><span>("Heart", "Love", "Boy", "Mary", "Paul", "Merry", "Jacky"); </span></span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">lookingFor</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">"Albert"</font></span><span>; </span> </li> <li class=""><span> </span></li> <li class="alt"><span>if (in_array($lookingFor, $namesArray)) { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "找到了!"; </span></li> <li class=""><span> </span></li> <li class="alt"><span>} else { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "在数组中找不到你要找的值!"; </span></li> <li class=""><span> </span></li> <li class="alt"><span>} </span></li> <li class=""><span> </span></li> <li class="alt"><span>?> </span></li> </ol>
If you change the value of the variable $lookingFor to "Mary "Then execute it again, and this time the screen will display "You've found it!" because the value "Mary" does exist in the $namesArray array. If you want to know the total number of elements contained in the array, then you can use the easy-to-use count() function:
The value of the variable $count will be 7.
The above is the specific application method of PHP function in_array().