PHP/Data Structure/array push — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 10:37, 26 мая 2010

Adding an Element to the End of an Array

 
<?php
  $languages = array();
  
  $languages[] = "German";
  $languages[] = "French";
  $languages[] = "Spanish";
  
  printf("<p>Languages: %s.</p>\n", implode(", ", $languages));
?>
<?php
  $languages = array();
  array_push($languages, "German", "French", "Spanish");
  printf("<p>Languages: %s.</p>\n", implode(", ", $languages));
?>



Adding array elements

 
<html>
 <body>
 <ol>
 <?php
  $arr = array( "Red ","Green ","Blue" );
  array_unshift( $arr, "Cyan", "Magenta" );
  array_push( $arr, "Yellow", "Black" );
  
  foreach( $arr as $value)
  {
    echo( "<li>Do you like $value ?</li>");
  }
  ?>
  </ol>
 </body>
</html>



array_push() function appends one or more values onto the end of the array.

 
//Its syntax is: int array_push(array array, mixed var, [. . . ])
<?
    $languages = array("A", "B", "C");
    array_push($languages, "Russian", "German", "Gaelic");
    print_r($languages);
?>
==
array_pop() function removes a value from the end of the array. This value is then returned. 
//Its syntax is: mixed array_pop(array array)
//Each iteration of array_pop() will shorten the length of the array by 1. 
<?
    $languages = array ("Spanish", "English", "French", "Gaelic");
    $a_language = array_pop ($languages); 
    print $a_language;
    $a_language = array_pop ($languages);
    print_r( $a_language); 
?>



array_push( ) pushes value onto the end of the array

 
//int array_push ( array &arr, mixed var [, mixed ...] )
<?
    $firstname = "Johnny";
    $names = array("Timmy", "Bobby", "Sam", "Tammy", "Joe");
    array_push($names, $firstname);
?>



Push one or more elements onto the beginning of array

 
<?
$queue = array("p1", "p3");
array_unshift($queue, "p4", "p5", "p6");
?>



Push one or more elements onto the end of array

 
<?
$stack = array (1, 2);
array_push($stack, "+", 3);
?>