|
 |
array_shift (PHP 4, PHP 5) array_shift --
Извлечь первый элемент массива
Описаниеmixed array_shift ( array &array )
array_shift() извлекает первое значение массива
array и возвращает его, сокращая размер
array на один элемент.
Все числовые ключи будут изменены таким образом, что нумерация массива начнётся с нуля,
в то время как строковые ключи останутся прежними. Если array пуст
(или не является массивом), будет возвращён NULL.
Замечание: Эта функция
сбрасывает указатель массива после использования.
Пример 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().
array_shift
bmr at ediweb dot org
31-May-2006 07: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.
lussnig at smcc dot de
21-Oct-2005 01:06
Warning array_shift take an argument of type array but it seems to be defined as array_shift(&$argument) since php-5.0.5 it does not take any function as argument. Even not if the function return an array !!!
lussnig at smcc dot de
21-Oct-2005 12:28
Warning: since php-5.0.5 there is an change.
Invalid is now array_shift(preg_split())
while
$temp = preg_split();
array_shift($temp)
is valid since call with reference.
groups at 8legs dot co dot nz
12-Oct-2005 01:29
As of version 5.0.5 it has been decreed that array_shift (and other methods that manipulate an array, like: array_pop, array_push) can no longer accept a reference, only a value.
For example:
Until 5.0.5 this was perfectly acceptable:
$first_element = array_shift(functionThatReturnsAnArray());
now it would have to look a little like this:
$arbitrary_array = functionThatReturnsAnArray()
$first_element = array_shift($arbitrary_array);
or
$first_element = array_shift($arbitrary_array = functionThatReturnsAnArray());
The change apparently has something to do with possible memory corruption but that sounds like a cop out to me. Fix the memory corruption if it's a problem, don't break a widely used and hither-to perfectly legitimate piece of syntax, then foist it on an unsuspecting community in a minor version change. Very unimpressed with the cavalier attitude regarding this issue.
19-Sep-2005 07:57
<?php
function create_relative_path($inSourcePath, $inRefPath)
{
$s_parts = explode('/', $inSourcePath);
$r_parts = explode('/', $inRefPath);
while ($s_parts[0] === $r_parts[0])
{
array_shift($s_parts);
array_shift($r_parts);
}
while ($s_parts[0])
{
array_unshift($r_parts, '..');
array_shift($s_parts);
}
return implode('/', $r_parts);
}
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';
$rel_path = create_relative_path($sp, $rp);
'../../../MyLibraries/lib_script.php'
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com
27-Jul-2005 05: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 06: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 04: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 11: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 12: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
17-Oct-2003 08: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 10: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 02: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.
| |