Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: array_shift - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net

search for in the

array_slice" width="11" height="7"/> <array_search
Last updated: Mon, 05 Feb 2007
view this page in

array_shift

(PHP 4, PHP 5)

array_shift — 配列の先頭から要素を一つ取り出す

説明

mixed array_shift ( array &array )

array_shift() は、array の最初の値を取り出して返します。配列 array は、要素一つ分だけ短くなり、全ての要素は前にずれます。 array が空の場合 (または配列でない場合)、 NULL が返されます。

注意: この関数は、 配列 (array) ポインタを使用した後にリセット (reset()) します。

例 255. 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
François
28-Oct-2006 12:35
Note that array_shift() can be rather time consuming. Whenever possible, you should consider using array_slice() instead.
Consider the following code :

$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
array_shift($hitsArray);
$monthlyHits++;
}
}

This could be replaced by :
$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
$monthlyHits++;
}
}
$monthlyHits = array_slice($hitsArray,$monthlyHits);

Here is a benchmark I did on a 10 000 rows array :
First method, 9000 mili-seconds.
Second method, 4 mili-seconds
alreece45 at yahoo dot com
10-Aug-2006 12:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val
= array_shift(preg_split());

?>

or

<?php

$val
= array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return
reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org
31-May-2006 11:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
20-Sep-2005 11:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
  
// break strings at slashes
  
$s_parts            = explode('/', $inSourcePath);
  
$r_parts            = explode('/', $inRefPath);
  
  
// delete items up to the first non-equal part
  
while ($s_parts[0] === $r_parts[0])
   {
      
array_shift($s_parts);
      
array_shift($r_parts);
   }
  
  
// add wild card to r_parts for each remaining
   // item of s_parts
  
while ($s_parts[0])
   {
      
array_unshift($r_parts, '..');
      
array_shift($s_parts);
   }
  
   return
implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//    Given a source path $sp generates the relative
//    location of $rp. $sp could be assigned using
//    $_SERVER['PHP_SELF'] but it's hardcoded for
//    the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com
27-Jul-2005 09:48
Im using this function to browse arrays from database. For example data:
<?php
$data
= array(
     array(
'row 1-cell 1','row 1-cell 2'),
     array(
'row 2-cell 1','row 2-cell 2'),
     array(
'row 3-cell 1','row 3-cell 2'),
);

while(
$row=array_shift($data)) {
     echo
$row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com
20-Apr-2005 10:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 09: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
15-Dec-2004 04: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
alex at netflex dot nl
14-Mar-2003 03: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)

array_slice" width="11" height="7"/> <array_search
Last updated: Mon, 05 Feb 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites