auto increment, self-decreasing in php

Wrote in the official PHP manual:

PHP supports C-style pre/post increment and decrement operators.

The first note: The increment/decrement operator does not affect Boolean values. Decreasing the NULL value has no effect, but the result of incrementing NULL is 1.

In others: In the increment/decrement operation, the operand is not converted to an integer and then operated. If the operand is a boolean, the result is returned directly.

Increment/decrement Boolean:
$a = TRUE;
var_dump(++$a); // bool(true)
$a = TRUE;
var_dump(--$a); // bool(true)
$b = FALSE;
var_dump(++$b); // bool(false)
$b = FALSE;
var_dump(--$b); // bool(false)
Increment/decrement NULL:
$a = NULL;
var_dump(++$a); // int(1) 
$a = NULL;
var_dump(--$a); // NULL

When dealing with the arithmetic of character variables, PHP follows the conventions of Perl, not C.

For example, in Perl:
$a = 'Z';
$a++;

Will turn $a into ‘B’, and in C:

a = 'Z';
a++;

Will change to a ‘[‘(‘Z’ has an ASCII value of 90, ‘[‘ has an ASCII value of 91).

Note that character variables can only be incremented, not decremented, and only support pure letters (a-z and A-Z).

For example:

$a="9D9"; 
var_dump(++$a);  // string(3) "9E0"

However, there is another trap here:

$a="9E0"; 
echo ++$a;  // 10

To install the above rules, you should output 9E1, but here it outputs 10. WTF!!!?
If we write this, most people will know why.

$a = "9E0"; 
var_dump(++$a);  // float(10)

The type of $a is floating-point, that is, 9E0 is the scientific notation of floating-point numbers, that is, 9 * 10^0 = 9, and 9 is self-incrementing, and the result is of course 10.

Now the problem is coming again:

$l = "Z99";
$l++; 

What is the result? The result is “AA00” according to the rules of the perl language.
There is one more note:

Increment/decrement of other character variables is invalid, and the original string does not change.
This will not explain.
The last note:

$a = '012';
$a++;
var_dump($a);

The result is ‘013’? 13?11?
The result of this paragraph is int(13), and the string ‘012’ is not treated as octal.

$a = 012;   // Octal, decimal 10
$b = "012"; // Convert to integer as decimal 12

What if it starts with 0x?

$a = '0x1A';
$a++;
var_dump($a);   // int(27)

WTF! Actually, I don’t follow the routine. The beginning of 0 is not considered to be octal, but the beginning of 0x is considered to be hexadecimal.

There is another octal trap in the integer in the official PHP documentation:

var_dump(01090); // Octal 010 = decimal 8

The explanation in this manual is:

Warning If an illegal number (ie 8 or 9) is passed to the octal number, the remaining digits are ignored.

In summary, PHP is the “best” language in the world.

Leave a Reply

Your email address will not be published. Required fields are marked *