user2417339
user2417339

Reputation:

Why can you increment characters in php

In PHP you can increment a character like this:

$b = 'a'++;

What I am wondering is from a language stand point why does that work? Does php interpret a character just as an ASCII value so incrementing it would just make the ASCII value 1 higher which would be the next letter in the alphabet?

Upvotes: 3

Views: 556

Answers (2)

blokeish
blokeish

Reputation: 601

Q: What I am wondering is from a language stand point why does that work?

A: Why is English written from left to right while Arabic right to left? That was the decision made by the people who designed the language. They might have their own reason to do so. I strongly believe that this was by design as if you do an Arithmetic addition ($a+1) it doesn't work the same way.

$a = 'a';

echo $a++; // output: 'a' , a is echoed and then incremented to 'b'
echo ++$a; // output: 'c' , $a is already 'b' and incremented first and then becomes 'c'

echo $a+1; // output: '1' , When in an arathamatic operation a string value is considered 0

// in short '++' seems to have been given special intrepretation with string
// which is equivalent to
echo $a = chr(ord($a)+1); // output: 'd' , the ascii value is incremented

Thanks for the question, I was not aware that '++' was applicable to strings.

Upvotes: 0

Alex Tartan
Alex Tartan

Reputation: 6836

Check this out: http://php.net/manual/en/language.operators.increment.php

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 alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Upvotes: 3

Related Questions