0

I used foreach, &, ++, +1.

In general, ++ is the same thing as +1. but ++ != +1 on this code(php7.3.4), why?

$data1 = $data2 = [
    ['id' => 0],
    ['id' => 1],
    ['id' => 2],
];
foreach ($data1 as $key => &$val) {
    $val['id'] = $val['id']++;
}
foreach ($data2 as $key => &$val) {
    $val['id'] = $val['id']+1;
}

var_dump($data1 == $data2); // false. why?

thank Nigel Ren

I change this code

foreach ($data1 as $key => &$val) {
    // $val['id'] = $val['id']++;
    $val['id']++;
}

the result is true. but i don't know why $val['id'] = $val['id']++ != $val['id']++?

nyx
  • 19
  • 6

1 Answers1

0

There is a basic difference between $i++ and ++$i.

pre-increment

++$i is Pre-increment, Increments $i by one, then returns $i

post-increment

$i++ is Post-increment, Returns $i, then increments $i by one

Addition

$i += 1 is Addition, adds 1, then return $i

Please have a look: https://www.php.net/manual/en/language.operators.increment.php

In your case use

$val['id']++; 

instead of

$val['id'] = $val['id']++;

Hope, it helps.

shirshak007
  • 363
  • 7
  • 1
    Yes, the result is `true`, but i don't know why `$val['id'] = $val['id']++` != `$val['id']++`? – nyx Nov 24 '21 at 08:45
  • This is because value of $val['id'] is assigned in the variable first, then incremented. here is one extra operations, but $val['id']++ is only one operation. – shirshak007 Nov 24 '21 at 08:48
  • I know this question is `$x = $x++` != `$x++` now, thank you very much! – nyx Nov 24 '21 at 08:50
  • Doesn't `val` get incremented after the assignment? – JMP Nov 24 '21 at 08:51
  • The document say `Returns $a, then increments $a by one.`. So `$x = $x++` == `$x = $x`. – nyx Nov 24 '21 at 08:58
  • 1
    `$x` is assigned `$x`, then `$x` is incremented by 1.@nyx – JMP Nov 24 '21 at 08:59
  • yes, you are right. [JMP](https://stackoverflow.com/users/4361999/jmp) – nyx Nov 24 '21 at 09:04