Character incrementing works, but adding is not. What for?

$a = 'a'; print ($a+1); print ($a++); print $a; 

Output: 1 ab

So, it’s clear that the increment operator did its job, but I don’t understand why the output is β€œ1” in the case of $a+1 . Can anyone explain?

+6
source share
4 answers

PHP is not C, so 'a' + 1 not 'b' .

'a' in the numerical context is 0 and 0+1 = 1 .

 php> echo (int)'a'; 0 

The fact that postfix / prefix increment operators work as if it were a C char seems to be an unpleasant "function" of PHP. Moreover, in this case the decrement operators are not op-op.

When you increment 'z' , it gets even worse:

 php> $a = 'z'; php> echo ++$a aa 
+7
source

The reason is that PHP handles variables in a certain way. This is a bit like Visual Basic.

The expression 'a' + 1 uses a mathematical complement. In this context, a interpreted as a number, so it will be considered 0 (if you are familiar with C, it kind of feeds the string "a" to atoi() ).

If you use the expression 'a' . 1 'a' . 1 , the result will be a1 because of it using string concatenation.

To get the expected result ( b ), you will need to use chr(ord('a') + 1) , where ord() explicitly returns the ASCII value of the (first) character.

$a++ is a special case, essentially an overload, considering the ascii value instead of the value itself as a variable.

+1
source

From http://php.net/manual/en/types.comparisons.php , "a" +1 is executed as 0 + 1. If some languages ​​(C #) will translate (string) + (int) to (string) + (string), PHP does the opposite: (int) + (int).

Instead of forcing string concatenation: "a" . 1 "a" . 1 returns 'a1'.

+1
source

When you do the addition, PHP tries to convert 'a' to an integer. Just as if you used atoi in C, 'a' is intepreted as 0. Therefore, 0 + 1 is 1.

0
source

Source: https://habr.com/ru/post/915009/


All Articles