★ wanayoo — archive 1999 http://fr.php.net/manual/ru/function.array-shift.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<array_searcharray_slice>
view the version of this page
Last updated: Sun, 20 Mar 2005

array_shift

(PHP 4 , PHP 5)

array_shift --  Извлечь первый элемент массива

Описание

mixed array_shift ( array &array )

array_shift() извлекает первое значение массива array и возвращает его, сокращая размер array на один элемент. Все числовые ключи будут изменены таким образом, что нумерация массива начнётся с нуля, в то время как строковые ключи останутся прежними. Если array пуст (или не является массивом), будет возвращён NULL.

Замечание: Эта функция reset() (сбрасывает) указатель array (массива) после использования.

Пример 1. Пример использования array_shift()

<?php
$stack
= array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

В результате в массиве $stack останется 3 элемента:

Array
(
   [0] => banana
   [1] => apple
   [2] => raspberry
)

и значение orange будет присвоено переменной $fruit.

См. также array_unshift(), array_push() и array_pop().



add a note add a note User Contributed Notes
array_shift
09-Feb-2005 01:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
  
reset($array);
  
$key = key($array);
  
$removed = $array[$key];
   unset(
$array[$key]);
   return
$removed;
}

?>
James McGuigan
14-Dec-2004 08:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array(
'title' => 'None'),
     array(
'title' => 'Unknown')
);

while ( (
$row = mysql_fetch_assoc($result))
     || (
$row = array_shift($defaults)))
{
  echo
$row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown
Rich at home dot nl
15-Jan-2004 09:55
How about using foreach? That was made for looping through arrays after all.

<?php
  $styles
= array('style1', 'style2', 'style3', ... 'stylen');

  while (
true)  {
   foreach (
$styles as $style) {
     if (
haveMoreToPrint()) print('<div class="' . $style . '">Some content</div>');
     else break
2;
   }
  }
?>
mina86 at tlen dot pl
18-Oct-2003 05:30
archangel, 04-Mar-2003 08:11:
This method is just waste of CPU, RAM and everything. Better would be:

<?php
$styles
= array('style1', 'style2', 'style3', ... 'stylen');
$styles_count = count($styles);

for (
$i = 0; haveMoreToPrint(); $i = ($i+1)%$styles_count) {
   print(
'<div class="'.$styles[$i].'">Some content</div>');
}
?>

It does the same thing but faster :)
alex at netflex dot nl
13-Mar-2003 07:55
Hi,

if you want to shift the first element of a large array (more than 10.000?) and it must realy fast then you can use this better:

<?php
reset
($array);
list(
$oldKey, $oldElement) = each($array);
unset(
$array[$oldKey]);
?>

note: the index wil not be changed (not reindexed)
archangel at uro dot mine dot nu
04-Mar-2003 11:11
Here's a fun little trick for cycling a set of items in the case where you want to say loop thorugh a set of styles for a tiled effect:

<?php
$styles
= array('style1', 'style2', 'style3', ... 'stylen');

while (
haveMoreToPrint())
{
  
array_push($styles, array_shift($styles));

   print(
'<div class="'.$styles[0].'">Some content</div>');
}
?>

And since the elements that are being shifted off go onto the end, there is no concern as to how many or how few styles your have or how many times you are going to cycle through them.  No counters, no nothin.

<array_searcharray_slice>
 Last updated: Sun, 20 Mar 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Wed Mar 23 05:13:59 2005 CET