2
<?php
 $s = "pa99";
 $s++;
 echo $s;
?>

The above code outputs to "pb00" What i wanted was "pa100" and so on.

But also in case its "pa", I want it to go to "pb" which works well with increment operator.

4
  • 1
    Wouldn't splitting the string, incrementing the number part, and then reassembling it be more accurate? Commented Aug 21, 2012 at 16:40
  • 2
    why not splitting them and increment them separately and concatenate them afterwards? Commented Aug 21, 2012 at 16:41
  • can't really split it apart, before hand, can i split after its a string? Commented Aug 21, 2012 at 16:43
  • @amitchhajer I guess understand what you need, check out my updated answer Commented Aug 21, 2012 at 17:01

3 Answers 3

12

You are, as Michael says, trying to increment a string - it Does Not Work That Way (tm). What you want to do is this:

<?php
 $s = "pa"; //we're defining the string separately!
 $i = 99; //no quotes, this is a number
 $i++;
 echo $s.$i; //concatenate $i onto $s
?>

There's no automated way to increment a string (aa, ab, etc) the way you're asking. You could turn each letter into a number between 1-26 and increment them, and then increment the previous one on overflow. That's kind of messy, though.

To separate the integer from the string, try this:

PHP split string into integer element and string

Sign up to request clarification or add additional context in comments.

3 Comments

Added a link to help you split it.
Sure thing. Just remember never to treat strings and integers as the opposite type unless you explicitly understand and desire the conversion methods and its consequences. Unexpected conversions are one way that vulnerabilities happen.
actually it was in my code, and found it after 2-3 months, the issue poped up and crashed few things.
4

From the docs:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Comments

0
<?php

  $s_letter = substr($s,0,2);
  $s_number = substr($s,2,9);

  $s_letter++; $s_number++;

  $s_result = $s_letter.$s_number;

  echo $s_result;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.