0

I have just asked a question on SO and found out I can make use of ++ to increment letters. I have now tried this:

$last_id = get_last_id();

echo gettype($last_id); //string

echo 'L_ID ->'.$last_id.'<br />'; //AAF

$next_id = $last_id++;

echo 'N_ID ->'.$next_id.'<br />';//AAF

The following example which I was given works fine:

$x = 'AAZ';
$x++;
echo $x;//ABA

What is going on? Must be the end of the work day...

Thanks all for any help

Community
  • 1
  • 1
Abs
  • 56,052
  • 101
  • 275
  • 409

2 Answers2

9

++ is a post increment operator, thus

$next_id = $last_id++;

assigns the current value of $last_id to $next_id, and then increments it. What you want is a pre-increment

$next_id = ++$last_id;
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
3

Putting ++ after a variable will increment it when the statement it's part of completes. You're assigning to $next_id the value of $last_id before it's incremented. Instead, use ++$last_id, which increments before the value of the variable is used.

  • That's not correct - the increment happens after evaluation, not when the whole statement completes. Thus $x=1; echo ($x++)*($x++); yields '2' – Paul Dixon Aug 25 '10 at 15:51
  • Also, operator precedence shows the order of evaluation: http://www.php.net/manual/en/language.operators.precedence.php – Paul Dixon Aug 25 '10 at 15:52