Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector variable value on PHP

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

like image 728
Javi Avatar asked Jan 14 '23 08:01

Javi


2 Answers

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.

like image 192
nickb Avatar answered Jan 22 '23 11:01

nickb


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.

like image 41
mcamara Avatar answered Jan 22 '23 10:01

mcamara