++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
Pre increment
Syntax:
++$variable_name
Example
++$a
Pre increment operator increments the variable value by 1 immediately.
pre_increment_demo.php
#!/usr/bin/php
<?php
$a = 10;
echo "Value of a is " . $a . "\n";
echo "Value of ++a is " . ++$a . "\n";
echo "Value of a is " . $a . "\n";
?>
Output
$./pre_increment_demo.php
Value of a is 10
Value of ++a is 11
Value of a is 11
Post increment
In case of post increment operator variable is evaluated first, and increment will be done later.
Syntax:
$variable++
Syntax
$a++
post_increment_demo.php
#!/usr/bin/php
<?php
$a = 10;
echo "Value of a is " . $a . "\n";
echo "Incrementing a twice in the same line " . $a++ . "\t" . $a++ . "\n";
echo "Value of a is " . $a . "\n";
?>
Output
$./post_increment_demo.php
Value of a is 10
Incrementing a twice in the same line 10 11
Value of a is 12
Pre decrement
Syntax:
--$variable_name
Example
--$a
Pre increment operator decrements the variable value by 1 immediately.
pre_decrement_demo.php
#!/usr/bin/php
<?php
$a = 10;
echo "Value of a is " . $a . "\n";
echo "Value of --a is " . --$a . "\n";
echo "Value of a is " . $a . "\n";
?>
Output
$./pre_decrement_demo.php
Value of a is 10
Value of --a is 9
Value of a is 9
Post decrement
In case of post decrement operator variable is evaluated first, and decrement will be done later.
Syntax:
$variable_name--
Example
$a--
post_decrement_demo.php
#!/usr/bin/php
<?php
$a = 10;
echo "Value of a is " . $a . "\n";
echo "Incrementing a twice in the same line " . $a-- . "\t" . $a-- . "\n";
echo "Value of a is " . $a . "\n";
?>
Output
$./post_decrement_demo.php
Value of a is 10
Incrementing a twice in the same line 10 9
Value of a is 8
No comments:
Post a Comment