如果有一个很大的数组,而你需要找出其中是否包含一个特定的元素,就可以使用PHP数组函数in_array()。下面的例子将显示“Not found in this array”,因为在一个名字为$namesArray的数组中查找Albert,而在$namesArray数组中不存在这样一个元素。
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><strong><font color="#006699"></font></strong></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>("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); </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 "You've found it!"; </span></li> <li class=""><span> </span></li> <li class="alt"><span>} else { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "Not found in this array!"; </span></li> <li class=""><span> </span></li> <li class="alt"><span>} </span></li> <li class=""><span> </span></li> <li class="alt"> <span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span> </li> </ol>
如果把$lookingFor的值改为Mary,就会得到“You've found it!”的信息,因为Mary是$namesArray数组中的一个元素。
如果要对一个数组中的元素个数进行计数,只要简单地使用PHP数组函数count()即可:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><strong><font color="#006699"></font></strong></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>("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); </span></span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">count</font></span><span class="attribute-value"><font color="#0000ff">count</font></span><span> = count($namesArray); </span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span> </li> </ol>
返回的$count的值为7。
可以在一个数组的开头或结尾处添加元素,还可以使用PHP数组函数array_merge()来建立一个包含二个或更多数组中元素的新数组,合并时,元素的顺序会按指定的顺序排列,如果原来的数组是被排过序的,在合并后需要对它重新排序。