PHP: Hypertext Preprocessor (original) (raw)
next
(PHP 4, PHP 5, PHP 7, PHP 8)
next — Advance the internal pointer of an array
Description
Parameters
array
The array being affected.
Return Values
Returns the array value in the next place that's pointed to by the internal array pointer, or [false](reserved.constants.php#constant.false)
if there are no more elements.
Warning
This function may return Boolean [false](reserved.constants.php#constant.false)
, but may also return a non-Boolean value which evaluates to [false](reserved.constants.php#constant.false)
. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Changelog
Version | Description |
---|---|
8.1.0 | Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. |
7.4.0 | Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. |
Examples
Example #1 Example use of next() and friends
<?php $transport = array('foot', 'bike', 'car', 'plane'); echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>o</mi><mi>d</mi><mi>e</mi><mo>=</mo><mi>c</mi><mi>u</mi><mi>r</mi><mi>r</mi><mi>e</mi><mi>n</mi><mi>t</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">mode = current(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">c</span><span class="mord mathnormal">u</span><span class="mord mathnormal">rre</span><span class="mord mathnormal">n</span><span class="mord mathnormal">t</span><span class="mopen">(</span></span></span></span>transport), PHP_EOL; // $mode = 'foot'; echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>o</mi><mi>d</mi><mi>e</mi><mo>=</mo><mi>n</mi><mi>e</mi><mi>x</mi><mi>t</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">mode = next(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">n</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">t</span><span class="mopen">(</span></span></span></span>transport), PHP_EOL; // $mode = 'bike'; echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>o</mi><mi>d</mi><mi>e</mi><mo>=</mo><mi>n</mi><mi>e</mi><mi>x</mi><mi>t</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">mode = next(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">n</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">t</span><span class="mopen">(</span></span></span></span>transport), PHP_EOL; // $mode = 'car'; echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>o</mi><mi>d</mi><mi>e</mi><mo>=</mo><mi>p</mi><mi>r</mi><mi>e</mi><mi>v</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">mode = prev(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">re</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mopen">(</span></span></span></span>transport), PHP_EOL; // $mode = 'bike'; echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><mi>o</mi><mi>d</mi><mi>e</mi><mo>=</mo><mi>e</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">mode = end(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mord mathnormal">d</span><span class="mopen">(</span></span></span></span>transport), PHP_EOL; // $mode = 'plane'; ?>
Notes
Note: The end of an array is indistinguishable from a bool
[false](reserved.constants.php#constant.false)
element. To properly traverse an array which may contain[false](reserved.constants.php#constant.false)
elements, see theforeach function. To still use next() and properly check if the end of the array has been reached, verify that the key() is[null](reserved.constants.php#constant.null)
.
See Also
- current() - Return the current element in an array
- end() - Set the internal pointer of an array to its last element
- prev() - Rewind the internal array pointer
- reset() - Set the internal pointer of an array to its first element
- each() - Return the current key and value pair from an array and advance the array cursor
Found A Problem?
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:
`
18 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....
}
`
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 :)
keys=arraykeys(keys = array_keys(keys=arraykeys(arr); keyIndexes=arrayflip(keyIndexes = array_flip(keyIndexes=arrayflip(keys);$return = array(); if (isset($keys[$keyIndexes[$key]-1])) return[]=return[] = return[]=keys[$keyIndexes[$key]-1]; if (isset($keys[$keyIndexes[$key]+1])) return[]=return[] = return[]=keys[$keyIndexes[$key]+1]; return $return; }?>`
7 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.
key=null,key = null, key=null,arRelated = array(), $cntRelated = 2) { if($count > 0 && isset($key)) { keyL=keyL = keyL=count - 1; $keyR = 1; $arResult = array(); for($i = 1; i<=i <= i<=cntRelated; $i++) { if($key == 0) { if(($i % 2) == 0) { curKey=curKey = curKey=count - $keyL; $keyL--; } else { curKey=curKey = curKey=count - $keyR; $keyR++; } } else { if($arRelated[$i] >= $count - 1) { $curKey = 0; } else { curKey=curKey = curKey=arRelated[$i] + 1; } } arResult[arResult[arResult[i] = $curKey; } return $arResult; } }$arr = range(0, 4); count=count(count = count(count=count(arr); foreach( arrasarr as arraskey => $v) { if($arRelated = array_neighbor($count, key,key, key,arRelated)) { arHeighbor[arHeighbor[arHeighbor[key]['RELATED'] = $arRelated; } } echo '';print_r($arHeighbor); echo ''; ?>
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
)
)
)
`
20 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:
Awork=A_work=Awork=array; //$A_work is a copy of $array but with its internal pointer set to the first element. PTR=current(PTR=current(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); } } ?>`
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:
array2=array2 = 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:
array2=array2 = 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=>key => key=>value){
echo key;<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><mi>y</mi><mn>2</mn><mostretchy="false">[</mo></mrow><annotationencoding="application/x−tex">array2[</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:1em;vertical−align:−0.25em;"></span><spanclass="mordmathnormal">a</span><spanclass="mordmathnormal"style="margin−right:0.02778em;">rr</span><spanclass="mordmathnormal">a</span><spanclass="mordmathnormal"style="margin−right:0.03588em;">y</span><spanclass="mord">2</span><spanclass="mopen">[</span></span></span></span>key]=key; <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><mi>y</mi><mn>2</mn><mo stretchy="false">[</mo></mrow><annotation encoding="application/x-tex">array2[</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mord">2</span><span class="mopen">[</span></span></span></span>key] = key;<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><mi>y</mi><mn>2</mn><mostretchy="false">[</mo></mrow><annotationencoding="application/x−tex">array2[</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:1em;vertical−align:−0.25em;"></span><spanclass="mordmathnormal">a</span><spanclass="mordmathnormal"style="margin−right:0.02778em;">rr</span><spanclass="mordmathnormal">a</span><spanclass="mordmathnormal"style="margin−right:0.03588em;">y</span><spanclass="mord">2</span><spanclass="mopen">[</span></span></span></span>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=arrayvalues(array2 = array_values(array2=arrayvalues(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 arraynorcopythepointertoarray nor copy the pointer to arraynorcopythepointertoarray2. Have a look on this.
I Hope this was a little helpfull.
`
bm at ANTISPAM dot solidwave dot com ¶
21 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
`
jbeauwalker at gmail dot com ¶
8 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.
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:
Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
`
7 years ago
`a more readable version of papipo's has_next function:
hasnext=isarray(has_next = is_array(hasnext=isarray(array) && next($array) !== false; return $has_next; } ?>OR
hasnext=next(has_next = next(hasnext=next(array) !== false; } return $has_next; } ?>`
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.
'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); } ?>`
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 ?>
3 years ago
`This is the best example of using next in a loop
'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); ?>`
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.
keys=arraykeys(keys = array_keys(keys=arraykeys(arr); keyIndexes=arrayflip(keyIndexes = array_flip(keyIndexes=arrayflip(keys);$return = array(); if (isset($keys[$keyIndexes[$key]-1])) { return[]=return[] = return[]=keys[$keyIndexes[$key]-1]; } else { return[]=return[] = return[]=keys[sizeof($keys)-1]; } if (isset( keys[keys[keys[keyIndexes[$key]+1])) { return[]=return[] = return[]=keys[$keyIndexes[$key]+1]; } else { return[]=return[] = return[]=keys[0]; } return $return; } ?>`
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.
array,array, array,currentKey) { if (!isset($array[$currentKey])) { return false; } $nextElement = false; foreach ($array as key=>key => key=>item) { nextElement=next(nextElement = next(nextElement=next(array); if ($key == $currentKey) { break; } } return $nextElement; } ` [ **_darkside at i dot ua_**](#79750)[ ¶](#79750) **17 years ago** `This class implements simple operations with array count = 0; } public function add ($step) {$this->count++; this−>all[this->all[this−>all[this->count] = $step; } public function setCurrent ($step) {reset($this->all); for ($i=1; i<=i<=i<=this->count; $i++) { if ($this->all[$i]==$step) break; next($this->all); } this−>curr=current(this->curr = current(this−>curr=current(this->all); } public function getCurrent () { return $this->curr; } public function getNext () {self::setCurrent($this->curr); return next($this->all); } } ?>usage example:
add('one'); $steps->add('two'); $steps->add('three'); $steps->setCurrent('one'); echo $steps->getCurrent().""; echo $steps->getNext()."
"; $steps->setCurrent('two'); echo $steps->getCurrent()."
"; echo $steps->getNext()."
"; ?>
`
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=>key => key=>value)
{
array[array[array[key] = '...';
}
`
andy at andysdrawings dot co dot uk ¶
6 years ago
`brentimus' array_set_pointer function will only work if the array value is unique in the array, and none of the array values are FALSE. It would be more reliable to use key() instead of current(). For similar reasons it's better to check key() after calling next() to determine whether the next() element "exists". Simply checking the value returned by next() will produce a false negative when looking at, for example, the first element of the array: ['one', 0, 'three']
However, it also turns out that the copied array retains the original array's pointer, so array_set_pointer is not actually required here. The following should work:
Awork=A_work = Awork=array; // AworkisacopyofA_work is a copy of Aworkisacopyofarray including its internal pointer. next($A_work); if (key($A_work) === NULL) return false; else return true; } ?>`
9 years ago
After dealing with the fact that next() will either returns FALSE when there is no further element in the array or if the element itself is FALSE, I finally find a way to do a has_next() method, which will never fails. You can ignore and/or downvote my last comment, this it will be deleted. Here is the code that work : <?php function has_next(array $a){ return next($a) !== false ?: each($a) !== false; } ?>