PHPのお勉強!

PHP TOP

next

(PHP 4, PHP 5, PHP 7, PHP 8)

next配列の内部ポインタを進める

説明

next(array|object &$array): mixed

next() は、ひとつの違いを除いて current() と同じです。 next() は要素を返す前に内部配列ポインタをひとつ先に進めます。 つまり、次の配列要素を返すとともに内部配列ポインタをひとつ進めるということです。

パラメータ

array

対象となる配列。

戻り値

内部配列ポインタが指す場所の次の場所の値を返します。 それ以上要素がない場合は false を返します。

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

変更履歴

バージョン 説明
8.1.0 この関数を object に対してコールすることは、推奨されなくなりました。 object に対して最初に get_mangled_object_vars() を使って配列に変換するか、ArrayIterator のような Iterator を実装したクラスのメソッドを使ってください。
7.4.0 SPL クラスのインスタンスは、プロパティを持たない空のオブジェクトのように扱われるようになりました。これより前のバージョンでは、この関数と同じ名前の Iterator のメソッドをコールしていました。

例1 next() および類似関数の使用例

<?php
$transport
= array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>

注意

注意: 配列の最後の要素に対してこの関数を実行した結果は、 次の要素が bool false だった場合と区別できません。 false 要素を含む配列を順に処理するには、foreach 関数を参照ください。 それでも next() 関数を使い、 適切に配列の最後に達していることをチェックするには、 key() 関数の結果が null であることを確認するようにしてください。

参考

  • current() - 配列内の現在の要素を返す
  • end() - 配列の内部ポインタを最終要素にセットする
  • prev() - 内部の配列ポインタをひとつ前に戻す
  • reset() - 配列の内部ポインタを先頭の要素にセットする
  • each() - 配列から現在のキーと値のペアを返して、カーソルを進める

add a note

User Contributed Notes 19 notes

up
19
JumpIfBelow
7 years ago
Now from PHP 7.2, the function "each" is deprecated, so the has_next I've posted is no longer a good idea. There is another to keep it simple and fast:

<?php
function has_next(array $_array)
{
return
next($_array) !== false ?: key($_array) !== null;
}
?>
up
8
gg2005 at gmail dot com
17 years ago
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
if (something I don't like about $thing) {
next;
}
blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
if (something I don't like about $thing) {
continue;
}
blah....
}
up
5
court shrock
20 years ago
This code returns neighbors of the specified key. The result will be empty if it doesn't have any neighbors. My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array. Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
krsort($arr);
$keys = array_keys($arr);
$keyIndexes = array_flip($keys);

$return = array();
if (isset(
$keys[$keyIndexes[$key]-1]))
$return[] = $keys[$keyIndexes[$key]-1];
if (isset(
$keys[$keyIndexes[$key]+1]))
$return[] = $keys[$keyIndexes[$key]+1];

return
$return;
}

?>
up
2
nigra
6 years ago
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($count, $key = null, $arRelated = array(), $cntRelated = 2)
{
if(
$count > 0 && isset($key))
{
$keyL = $count - 1;
$keyR = 1;
$arResult = array();
for(
$i = 1; $i <= $cntRelated; $i++)
{
if(
$key == 0)
{
if((
$i % 2) == 0)
{
$curKey = $count - $keyL;
$keyL--;
}
else
{
$curKey = $count - $keyR;
$keyR++;
}
}
else
{
if(
$arRelated[$i] >= $count - 1)
{
$curKey = 0;
}
else
{
$curKey = $arRelated[$i] + 1;
}
}
$arResult[$i] = $curKey;
}
return
$arResult;
}
}

$arr = range(0, 4);
$count = count($arr);

foreach(
$arr as $key => $v)
{
if(
$arRelated = array_neighbor($count, $key, $arRelated))
{
$arHeighbor[$key]['RELATED'] = $arRelated;
}
}

echo
'<pre>';print_r($arHeighbor); echo '</pre>';
?>
Array
(
[0] => Array
(
[RELATED] => Array
(
[1] => 4
[2] => 1
)

)

[1] => Array
(
[RELATED] => Array
(
[1] => 0
[2] => 2
)

)

[2] => Array
(
[RELATED] => Array
(
[1] => 1
[2] => 3
)

)

[3] => Array
(
[RELATED] => Array
(
[1] => 2
[2] => 4
)

)

[4] => Array
(
[RELATED] => Array
(
[1] => 3
[2] => 0
)

)

)
up
3
brentimus
19 years ago
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
$A_work=$array; //$A_work is a copy of $array but with its internal pointer set to the first element.
$PTR=current($array);
array_set_pointer($A_work, $PTR);

if(
is_array($A_work))
{
if(
next($A_work)===false)
return
false;
else
return
true;
}
else
return
false;
}

function
array_set_pointer(&$array, $value)
{
reset($array);
while(
$val=current($array))
{
if(
$val==$value)
break;

next($array);
}
}
?>
up
1
double at dumpit dot de
15 years ago
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
$array
= array('zero','one','two','three','four','five','six','seven');
$array2 = $array;
next($array);
echo
key($array);
echo
key($array2);

// will output:
// 1
// 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
$array
= array('zero','one','two','three','four','five','six','seven');
next($array);
$array2 = $array;
echo
key($array);
echo
key($array2);

// will output:
// 1
// 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

$array
= array('zero','one','two','three','four','five','six','seven');
next($array);
$array2 = array();
foreach(
$array AS $key => $value){
echo
$key;
$array2[$key] = $value;
}
echo
var_dump(key($array));
echo
key($array2);

// will output for foreach:
// 0 1 2 3 4 5 6 7
// and for the keys
// NULL
// 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

$array
= array('zero','one','two','three','four','five','six','seven');
next($array);
$array2 = array_values($array);
echo
key($array);
echo
key($array2);

// will output:
// 1
// 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
up
1
bm at ANTISPAM dot solidwave dot com
20 years ago
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer. This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element. You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach
up
0
jbeauwalker at gmail dot com
3 months ago
I suggest that a WARNING that next() should not be used within a foreach loop should be included in the main body of the documentation at the top. At one time, it seems to have been there, but I spent hours trying to solve the bizarre problems that result from this combination, only to stumble on a clue to it on another site, that seem to suggest that it was originally clearly identified. If you look hard, this problem is referenced in some notes, but one doesn't expect to look there for something so basic.
up
1
papipo's gmail account
20 years ago
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
if (
is_array($array)) {
if (
next($array) === false) {
return
false;
} else {
return
true;
}
} else {
return
false;
}
}

$array = array('fruit', 'melon');
if (
has_next($array)) {
echo
next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
up
0
notImportant
6 years ago
a more readable version of papipo's has_next function:

<?php
function has_next($array) {
$has_next = is_array($array) && next($array) !== false;

return
$has_next;
}
?>

OR

<?php
function has_next($array) {
$has_next = false;
if(
is_array($array)) {
$has_next = next($array) !== false;
}

return
$has_next;
}
?>
up
-1
tecdoc at ukr dot net
1 year ago
It is good example how to loop array by current() and next() functions from php key() manual. In my opinion, this particular example would be better placed in current() and next() than key() manuals.

<?php
$array
= array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
reset($array); // prepare array for cycle
while ($fruit_name = current($array)) {
if (
$fruit_name == 'apple') {
echo
key($array), "\n";
}
next($array);
}
?>
up
-1
tecdoc at ukr dot net
1 year ago
Be attentive! It is possibility to lose the array pointer with next() and prev();
<?php
// example
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

reset($array); // prepare array

$row = current($array);
var_dump($row); // 'apple'

$row = prev($array);
var_dump($row); // false. The array pointer is lossed!

$row = next($array); // it is not possible to return to the previous (first/last element)!
var_dump($row); // false
?>
up
-2
Anonymous
2 years ago
This is the best example of using next in a loop

<?php
$array
= array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
reset($array); // prepare array for cycle
while ($fruit_name = current($array)) {
if (
$fruit_name == 'apple') {
echo
key($array), "\n";
}
next($array);
}
reset($array);
?>
up
-1
lukasz at karapuda dot com
20 years ago
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
$keys = array_keys($arr);
$keyIndexes = array_flip($keys);

$return = array();
if (isset(
$keys[$keyIndexes[$key]-1])) {
$return[] = $keys[$keyIndexes[$key]-1];
}
else {
$return[] = $keys[sizeof($keys)-1];
}

if (isset(
$keys[$keyIndexes[$key]+1])) {
$return[] = $keys[$keyIndexes[$key]+1];
}
else {
$return[] = $keys[0];
}

return
$return;
}
?>
up
-1
Mikhail
5 years ago
This function returns next element in array after your key or false if it last or key doesn't exists in array.

<?php

function nextElement(array $array, $currentKey)
{
if (!isset(
$array[$currentKey])) {
return
false;
}
$nextElement = false;
foreach (
$array as $key => $item) {
$nextElement = next($array);
if (
$key == $currentKey) {
break;
}
}

return
$nextElement;
}
up
-2
darkside at i dot ua
17 years ago
This class implements simple operations with array

<?php
class Steps {

private
$all;
private
$count;
private
$curr;

public function
__construct () {

$this->count = 0;

}

public function
add ($step) {

$this->count++;
$this->all[$this->count] = $step;

}

public function
setCurrent ($step) {

reset($this->all);
for (
$i=1; $i<=$this->count; $i++) {
if (
$this->all[$i]==$step) break;
next($this->all);
}
$this->curr = current($this->all);

}

public function
getCurrent () {

return
$this->curr;

}

public function
getNext () {

self::setCurrent($this->curr);
return
next($this->all);

}

}
?>

usage example:

<?php
$steps
= new Steps();
$steps->add('one');
$steps->add('two');
$steps->add('three');
$steps->setCurrent('one');
echo
$steps->getCurrent()."<br />";
echo
$steps->getNext()."<br />";
$steps->setCurrent('two');
echo
$steps->getCurrent()."<br />";
echo
$steps->getNext()."<br />";
?>
up
-2
ThinkMedical at Gmail dot com
16 years ago
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
$array[$key] = '...';
}