Well, ths is a really newbie question, but couldn't find the proper keywords to get the answer.
I have a vector variable, $p.
I want to achieve this:
$n = 5;
$prev = $p[$n--];
$actual = $p[$n];
$next = $p[$n++];
The values i want should be:
$prev = 4;
$actual = 5;
$next = 6;
Instead of that, i get:
$prev = 5;
$actual = 4;
$next = 4;
I know i'm missing something, but i couldn't figure it out.
Thanks in advance
Just do the math yourself:
$prev = $p[$n - 1];
$actual = $p[$n];
$next = $p[$n + 1];
If you must use increment / decrement operators (for some strange reason), you can use:
$prev = $p[--$n];
$actual = $p[++$n];
$next = $p[++$n];
Note that your original code was failing, as jeremy points out, because increment and decrement operators modify the original value of the variable.
At the first search:
$prev = $p[$n--]
You are changing the value of n for the next operations, decreasing it by one. In
$next = $p[$n++];
You are increasing it again so n value is the same as the beginning. You should do what nickb told.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With