PHP/Data Structure/array shift
Содержание
array_shift() function operates much like array_pop()
//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);
?>
array_shift( ) function returns the value from the front of the array while also removing it from the array.
<?
$names = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Joe");
$firstname = array_shift($names); // "Johnny"
var_dump($names);
?>
Removing the First Element of an Array with array_shift()
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<br />";
print "there are ".count( $an_array )." elements in \$an_array <br />";
}
?>
Removing the First or Last Element from an Array
<?php
$languages = array("French","German","Russian","Chinese","Hindi", "Quechua");
printf("<p>Original array:</p><pre>%s</pre>\n", var_export($languages, TRUE));
$removed = array_shift($languages);
printf("<p>Using array_shift():<br />Removed element: %s</p><pre>%s</pre>\n",
$removed, var_export($languages, TRUE));
$removed = array_pop($languages);
printf("<p>Using array_pop():<br />Removed element: %s</p><pre>%s</pre>\n",
$removed, var_export($languages, TRUE));
unset( $languages[count($languages) - 1] );
printf("<p>Using unset() and count():</p><pre>%s</pre>\n",
var_export($languages, TRUE));
?>