PHP/Data Structure/array shift

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

array_shift() function operates much like array_pop()

   <source lang="html4strict">

//array_shift() function removes one element from the left side of the array. //All remaining array elements are shifted one unit toward the left side of the array. //array_shift() has the same syntax as array_pop(): <?

   $languages = array("Spanish", "English", "French", "Russian");
   $a_language = array_shift($languages); 
   print_r($a_language);

?>

 </source>
   
  


array_shift( ) function returns the value from the front of the array while also removing it from the array.

   <source lang="html4strict">

<?

   $names = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Joe");
   $firstname = array_shift($names); // "Johnny"
   var_dump($names);

?>

 </source>
   
  


Removing the First Element of an Array with array_shift()

   <source lang="html4strict">

array_shift() removes and returns the first element of an array passed to it as an argument. <?php $an_array = array("a", "b", "c"); while ( count( $an_array ) ) {

 $val = array_shift( $an_array);
 print "$val
"; print "there are ".count( $an_array )." elements in \$an_array
";

} ?>

 </source>
   
  


Removing the First or Last Element from an Array

   <source lang="html4strict">

<?php

 $languages = array("French","German","Russian","Chinese","Hindi", "Quechua");
printf("

Original array:

%s
\n", var_export($languages, TRUE));
 $removed = array_shift($languages);
printf("

Using array_shift():
Removed element: %s

%s
\n",
         $removed, var_export($languages, TRUE));
         
 $removed = array_pop($languages);
printf("

Using array_pop():
Removed element: %s

%s
\n",
         $removed, var_export($languages, TRUE));
         
 unset( $languages[count($languages) - 1] );
printf("

Using unset() and count():

%s
\n",
         var_export($languages, TRUE));

?>

 </source>