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

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

3 Comments

Or he could break it into two statements: $last_id++; $next_id = $last_id;
Ah I did not know, that. Every time I ask a question on SO, it highlights how little I know about PHP! Thank you Paul.
@Abs: Also, these operators exist in a number of other languages, and their behaviour there is similar.
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.

2 Comments

That's not correct - the increment happens after evaluation, not when the whole statement completes. Thus $x=1; echo ($x++)*($x++); yields '2'
Also, operator precedence shows the order of evaluation: php.net/manual/en/language.operators.precedence.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.