当你使用下面的例子中首先示范如何使用PHP函数array_push()在数组的尾端新增元素:
<ol class="dp-xml"> <li class="alt"><span><span><? /* 首先我们建立一个数组 */ </span></span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">fruitArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array</font></span><span>("apple", "orange", "banana", "Peach", "pear"); </span> </li> <li class=""><span> </span></li> <li class="alt"><span>/* 使用array_push()函数在原有数组尾端新增一些元素 */ </span></li> <li class=""><span> </span></li> <li class="alt"><span>array_push($fruitArray, "grape", "pineapple", "tomato"); </span></li> <li class=""><span> </span></li> <li class="alt"><span>/* 现在把该数组的所有元素的键(key)与值(value)都显示在网页上 */ </span></li> <li class=""><span> </span></li> <li class="alt"><span>while (list($key,$value) = each($fruitArray)) { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "$key : $value<br>"; </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>
显示结果如下:
0 : apple
1 : orange
2 : banana
3 : Peach
4 : pear
5 : grape
6 : pineapple
7 : tomato
现在来示范如何运用PHP函数array_push()从数组的开头新增一些元素。下面的程序代码和前面一个例子几乎完全相同,唯一的差别只是这里使用的函数是array_unshift()而不是 array_push()。
<ol class="dp-xml"> <li class="alt"><span><span><? </span></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="attribute"><font color="#ff0000">fruitArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array</font></span><span>("apple", "orange", "banana", "Peach", "pear"); </span> </li> <li class=""><span> </span></li> <li class="alt"><span>/* 使用array_unshift()函数在原有数组开头新增一些元素 */ </span></li> <li class=""><span> </span></li> <li class="alt"><span>array_unshift($fruitArray, "grape", "pineapple", "tomato"); </span></li> <li class=""><span> </span></li> <li class="alt"><span>/* 现在把该数组的所有元素的键(key)与值(value)都显示在网页上 */ </span></li> <li class=""><span> </span></li> <li class="alt"><span>while (list($key,$value) = each($fruitArray)) { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "$key : $value<br>"; </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>
显示结果如下:
0 : grape
1 : pineapple
2 : tomato
3 : apple
4 : orange
5 : banana
6 : Peach
7 : pear
以上两段代码分别介绍了PHP函数array_push()在数组头尾增加元素的办法。