php increment/decrement operator

伊谢尔伦
Release: 2016-11-24 13:26:28
Original
1594 people have browsed it

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

Note: Increment/decrement operators do not affect Boolean values. Decrementing a NULL value has no effect, but increasing NULL results in 1.

Increment/Decrease Operator

Example

Name

Effect

++$a Prepend the value of $a by one, and then return $a.

$a++ followed by , returns $a, and then adds one to the value of $a.

--$a Subtracts the value of $a by one, and then returns $a.

$a-- After subtraction returns $a, and then decrements the value of $a by one.

A simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
Copy after login

When dealing with arithmetic operations on character variables, PHP follows Perl's habits instead of C's. For example, in Perl $a = 'Z'; $a++; will turn $a into 'AA', while in C, a = 'Z'; a++; will turn a into '['('Z' The ASCII value of '[' is 90, and the ASCII value of '[' is 91). Note that character variables can only be incremented, not decremented, and only pure letters (a-z and A-Z) are supported. Incrementing/decrementing other character variables is invalid and the original string will not change.

Example #1 Arithmetic operations involving character variables

<?php
$i = &#39;W&#39;;
for ($n=0; $n<6; $n++) {
    echo ++$i . "\n";
}
?>
Copy after login

The above routine will output:

X
Y
Z
AA
AB
AC
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!