Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using next in foreach loop

I am looping through an array using foreach.

In a particular situation I need to know the value of the next element before iteration comes to that(like a prediction) element. For that I am planning to use the function next().

In documentation I just noticed that next() advances the internal array pointer forward.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

If so will it affect my foreach loop?

like image 958
Quicksilver Avatar asked Jul 31 '13 06:07

Quicksilver


2 Answers

It will not affect your loop if you use it in this way

<?php

$lists = range('a', 'f');

foreach($lists as &$value) {
   $next = current($lists);
   echo 'value: ' . $value . "\n" . 'next: ' . $next . "\n\n";
}

OUTPUT

value: a next: b

value: b next: c

value: c next: d

value: d next: e

value: e next: f

value: f next:

like image 78
liyakat Avatar answered Sep 28 '22 02:09

liyakat


next() doesn't affect foreach(), period.

In PHP 7.2 at least,

$values = ['a', 'b', 'c', 'd', 'e'];

foreach ($values as $value) {
  next($values);
  $two_ahead = next($values);
  echo("Two ahead: $two_ahead\n");
  echo("Current value: $value\n");
}

Produces:

Two ahead: c
Current value: a
Two ahead: e
Current value: b
Two ahead: 
Current value: c
Two ahead: 
Current value: d
Two ahead: 
Current value: e

Also note that the foreach loop does not affect the position of next, either. They're independent.

If you have an array with sequential numeric keys (the default), then ops' answer is best for what you're trying to do. I merely answered the question.

like image 23
mlncn Avatar answered Sep 28 '22 03:09

mlncn