Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In general, ++ is the same thing as +1. Why ++ != +1 on this code?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading