1

Why do I get a different output with $key++ and $key+1?

What should I do to refer to the next element in the loop using foreach?

foreach($diff as $key=>$val) {

if(in_array($diff[$key],$common) && in_array($diff[$key+1],$common)) {}

if(in_array($diff[$key],$common) && in_array($diff[$key++],$common)) {}

}
Widor
  • 13,003
  • 7
  • 42
  • 64
SupaOden
  • 722
  • 4
  • 13
  • 41
  • 1
    Take a look at http://stackoverflow.com/questions/6400518/pre-incrementation-vs-post-incrementation – jprofitt Dec 21 '11 at 17:08

5 Answers5

4
  • $key + 1 returns $key + 1 and does not modify $key (see documentation).

  • $key++ returns $key and changes $key to $key + 1 (see documentation).

You should be using the former as there is no reason to modify $key.

2

$x++ returns the old value of $x (before the increment). For example, $x=3; print $x++; will print "3". It also modifies $x, so it's not the best choice unless that's your intent. (Here, incrementing would be pretty useless, particularly since the modified keys never see the outside of the loop.)

++$x would return the new value of $x. Like $x++, though, it's semantically wrong for just getting the next number, as it modifies $x.

Just stick with $x + 1.

cHao
  • 84,970
  • 20
  • 145
  • 172
0
$key+1

Always just adds 1 to the $key for that instance. It does not modify $key at all

$key++

Increments the $key value, and it retains that value when the next loop starts

Nonym
  • 6,199
  • 1
  • 25
  • 21
0

$key++ increments the value of $key by 1.

$key+1 adds 1 to the value of $key, but does not change it.

Widor
  • 13,003
  • 7
  • 42
  • 64
0

$key + 1 will add on to the key but actually increment $key.

$key++ will take the value of $key and after its been returned, then increment $key (after use).

Prisoner
  • 27,391
  • 11
  • 73
  • 102