Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_shift

array_shift

Shift an element off the beginning of array (PHP 4, PHP 5)
mixed array_shift ( array &array )

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned.

Note:

This function will reset() the array pointer after use.

Example 276. array_shift() example

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

This would result in $stack having 3 elements left:

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

and orange will be assigned to $fruit.


See also array_unshift(), array_push(), and array_pop().

Related Examples ( Source code ) » array_shift



Code Examples / Notes » array_shift

james mcguigan

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'] . "
";
}
?>
This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown


09-feb-2005 12: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;
}
?>


françois

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


c_prevost

no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.

lukasz dot dywicki del

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


richard

If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.
<?php
while($key = key($array))
{
    $value = array_shift($array);
    //code goes here
}
?>
its like foreach but each time the value is removed from the array so it eventually ends up empty
<?php
//example below
$airports = array
(
"LGW" => "London Gatwick",
"LHR" => "London Heathrow",
"STN" => "London Stanstead"
);
echo count($airports)." Airport in the array<br /><br />";
while($key = key($airports))
{
$value = array_shift($airports);
echo $key." is ".$value."<br />";
}
echo "<br />".count($airports)." Airport left in the array";
?>
Example Outputs:
3 Airport in the array
LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead
0 Airport left in the array


dmhouse

If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().

bmr

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.


baughmankr

I needed to remove the first set of keys and values from an associative array.  Had to write this function:
function shortenArray($_arr)
{
$i=1;
$_shorter=array();
foreach ($_arr as $k => $v)
{
if ($i != 1)
{
$_shorter[$k] = $v;
}
$i++;
}
return $_shorter;
}


alreece45

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.
}


nando_f

I believe the example for array_shift is incorrect.
The print_r has the wrong variable.
-NF


alex

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)


arturo {dot} ronchi {at} gmail {dot} com

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;
}


traps

For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.
The solution is to reference the first element before removing it with array_shift():
<?php
// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b
"; // outputs a = 1, b = 2
// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b
"; // outputs a = 2, b = 2
?>


ben

baughmankr at appstate dot edu, I think this is more efficient.
<?php
function array_shorten($arr)
{
 list($k) = array_keys($arr);
 unset($arr[$k]);
 return $arr;
}
?>


20-sep-2005 03: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));


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker