Home  >  Article  >  Backend Development  >  如何运用PHP函数array_push()实现数组元素的增加_PHP教程

如何运用PHP函数array_push()实现数组元素的增加_PHP教程

WBOY
WBOYOriginal
2016-07-15 13:29:091070browse

当你使用下面的例子中首先示范如何使用PHP函数array_push()在数组的尾端新增元素:

  1. <? /* 首先我们建立一个数组 */   
  2.  
  3. $fruitArray = array("apple", "orange", "banana", "Peach", "pear");    
  4.  
  5. /* 使用array_push()函数在原有数组尾端新增一些元素 */   
  6.  
  7. array_push($fruitArray, "grape", "pineapple", "tomato");    
  8.  
  9. /* 现在把该数组的所有元素的键(key)与值(value)都显示在网页上 */   
  10.  
  11. while (list($key,$value) = each($fruitArray)) {   
  12.  
  13. echo "$key : $value<br>";   
  14.  
  15. }    
  16.  
  17. ?>     

显示结果如下:

0 : apple

1 : orange

2 : banana

3 : Peach

4 : pear

5 : grape

6 : pineapple

7 : tomato

现在来示范如何运用PHP函数array_push()从数组的开头新增一些元素。下面的程序代码和前面一个例子几乎完全相同,唯一的差别只是这里使用的函数是array_unshift()而不是 array_push()。

  1. <?   
  2.  
  3. /* 首先我们建立一个数组 */   
  4.  
  5. $fruitArray = array("apple", "orange", "banana", "Peach", "pear");    
  6.  
  7. /* 使用array_unshift()函数在原有数组开头新增一些元素 */   
  8.  
  9. array_unshift($fruitArray, "grape", "pineapple", "tomato");    
  10.  
  11. /* 现在把该数组的所有元素的键(key)与值(value)都显示在网页上 */   
  12.  
  13. while (list($key,$value) = each($fruitArray)) {   
  14.  
  15. echo "$key : $value<br>";   
  16.  
  17. }    
  18.  
  19. ?>   

显示结果如下:

0 : grape

1 : pineapple

2 : tomato

3 : apple

4 : orange

5 : banana

6 : Peach

7 : pear

以上两段代码分别介绍了PHP函数array_push()在数组头尾增加元素的办法。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446378.htmlTechArticle当你使用 下面的例子中首先示范如何使用PHP函数array_push()在数组的尾端新增元素: <?/*首先我们建立一个数组*/ $ fruitArray = array ("apple","...
Statement:
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