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']++?
>Solution :
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.