PHP Tutorial 31 of 272
Introduction & Setup
- Introduction to PHP
- History of PHP
- Features of PHP
- Applications of PHP
- Advantages and Limitations of PHP
- PHP Installation on Windows
- PHP Installation on Linux
- PHP Installation on macOS
- Setting Up a PHP Project
- Hello World in PHP
- Basic PHP Syntax
- PHP Tags and Embedding HTML
- How PHP Works on a Web Server
- PHP CLI
- PHP Configuration and php.ini
Basics
- PHP Comments
- PHP Variables
- PHP Constants
- PHP Data Types
- PHP Type Juggling
- PHP Type Casting
- PHP Strict Types
- PHP Magic Constants
- PHP Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- String Operators
- PHP Increment and Decrement Operators
- PHP Ternary Operator
- Null Coalescing Operator
- Operator Precedence
- PHP Decision Making
- if Statement
- if-else Statement
- elseif Statement
- Nested if
- switch Statement
- match Expression
- Loops in PHP
- for Loop
- while Loop
- do-while Loop
- foreach Loop
- break Statement
- continue Statement
Functions
- PHP Functions
- User-Defined Functions
- Function Parameters
- Return Values
- Default Arguments
- Named Arguments
- Variable-Length Arguments
- Anonymous Functions
- Arrow Functions
- Callback Functions
- Recursive Functions
- Variable Functions
- Closures in PHP
- String Functions
- Math Functions
- Date and Time Functions
Arrays
- PHP Arrays
- Indexed Arrays
- Associative Arrays
- Multidimensional Arrays
- Array Iteration
- Adding and Removing Array Elements
- Sorting Arrays
- Searching Arrays
- Merging Arrays
- Array Filtering
- Array Mapping
- Array Reduction
- Array Destructuring
- Spread Operator with Arrays
- Array Functions Reference
Strings
- PHP Strings
- Single vs Double Quotes
- String Concatenation
- String Length
- String Comparison
- Substring Operations
- String Search
- String Replacement
- String Splitting and Joining
- String Formatting
- Multiline Strings
- Regular Expressions in PHP
- String Encoding and Decoding
Superglobals, Forms & Input
- PHP Superglobals
- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_REQUEST
- $_FILES
- $_SESSION
- $_COOKIE
- Form Handling in PHP
- Form Validation
- Required Fields Validation
- Email and URL Validation
- Sanitizing User Input
- CSRF Protection
File Handling
- PHP File Handling
- fopen()
- fclose()
- fread()
- fgets()
- fwrite()
- file_get_contents()
- file_put_contents()
- readfile()
- file_exists()
- filesize()
- unlink()
- Directory Handling
- File Uploads
- Secure File Uploads
- CSV File Handling
- JSON File Handling
OOP
- Classes and Objects in PHP
- Class Properties and Methods
- Constructors
- Destructors
- Access Modifiers
- public private protected
- Static Properties and Methods
- Inheritance
- Method Overriding
- Polymorphism
- Abstract Classes
- Interfaces
- Traits
- Namespaces
- Anonymous Classes
- Final Classes and Methods
- Readonly Classes and Properties
- Magic Methods
- Object Cloning
- Dependency Injection in PHP
Error & Exception Handling
- PHP Error Reporting
- Types of PHP Errors
- Warnings and Notices
- PHP Exceptions
- try-catch
- finally Block
- throw Expression
- Custom Exceptions
- set_error_handler()
- trigger_error()
- Logging Errors
- Debugging PHP Applications
Database & MySQL
- PHP MySQL Database Introduction
- Connecting PHP to MySQL
- MySQLi Extension
- PDO in PHP
- PDO Prepared Statements
- MySQL Transactions with PHP
- CRUD with PHP and MySQL
- Insert Form Data into MySQL
- Fetch Data from MySQL
- Update Data with PHP
- Delete Data with PHP
- Pagination with PHP and MySQL
- Database Error Handling
- SQL Injection Prevention
Sessions, Cookies & Authentication
- PHP Sessions
- Starting and Destroying Sessions
- Session Security
- PHP Cookies
- Secure Cookies
- Login System in PHP
- Password Hashing
- password_hash()
- password_verify()
- Remember Me Authentication
- Role-Based Access Control
JSON, XML & APIs
- JSON in PHP
- json_encode()
- json_decode()
- Working with JSON Files
- XML in PHP
- SimpleXML
- PHP REST API
- Building a JSON API
- Consuming REST APIs
- cURL in PHP
- HTTP Headers in PHP
- API Authentication
- JWT Authentication with PHP
Security
- PHP Security Best Practices
- Input Validation vs Sanitization
- SQL Injection
- Cross-Site Scripting (XSS)
- Cross-Site Request Forgery (CSRF)
- Session Fixation
- Clickjacking Protection
- Password Security
- Secure File Uploads
- Output Encoding
- Security Headers
- Secure HTTP Cookies
Testing & Debugging
- PHP Unit Testing
- PHPUnit
- PHPUnit Assertions
- Mocking in PHPUnit
- Integration Testing PHP
- Debugging with Xdebug
- Static Analysis with PHPStan
- Code Quality with PHP CS Fixer
Composer & Packages
- Composer Introduction
- composer.json
- Composer Dependencies
- Autoloading with Composer
- PSR-4 Autoloading
- Semantic Versioning
- Publishing a PHP Package
Modern PHP
- Scalar Type Declarations
- Return Type Declarations
- Nullable Types
- Union Types
- Intersection Types
- Type Declarations and Strictness
- Nullsafe Operator
- Match Expression
- Attributes in PHP
- Enumerations (Enums)
- Readonly Properties
- Readonly Classes
- Fibers
- Generators
- Iterators
- Closures
Frameworks & Ecosystem
- Laravel with PHP
- Symfony with PHP
- PHP MVC Architecture
- Laravel Routing
- Laravel Controllers
- Laravel Eloquent ORM
- Laravel Authentication
- Symfony Components
- WordPress PHP Development
- PHP Middleware
Practice & Projects
- PHP Basic Programs
- PHP Array Programs
- PHP Function Programs
- PHP String Programs
- PHP Date Programs
- PHP Classes Programs
- PHP JSON Programs
- PHP File System Programs
- PHP Exercises
- PHP Basic Quiz
- PHP Functions Quiz
- PHP Arrays Quiz
- PHP Forms Quiz
- PHP File Handling Quiz
- PHP OOP Quiz
- PDF Downloader Project
- Automatic File Downloader
- Image Resizer Project
- File Uploader Project
- Signup Form Project
- Admin Login Project
- Group Chat Application
- PHP REST API Project
- PHP Interview Questions
- PHP Cheat Sheet
PHP Increment and Decrement Operators
Learn how PHP increment and decrement operators work, including pre-increment, post-increment, pre-decrement, post-decrement, and practical examples.
On this page
PHP Increment and Decrement Operators
PHP provides increment (++) and decrement (--) operators to increase or decrease the value of a variable by one.
These operators are commonly used in:
- Loops
- Counters
- Array traversal
- Iterations
- Conditional logic
- Numeric calculations
PHP supports both prefix and postfix forms of increment and decrement operators.
++$x → Pre-increment
$x++ → Post-increment
--$x → Pre-decrement
$x-- → Post-decrement
The main difference is when the value is changed relative to when it is used in an expression.
PHP Increment Operator
The increment operator ++ increases a variable's value by 1.
For example:
<?php
$count = 5;
$count++;
echo $count;
?>
Output:
6
This:
$count++;
is equivalent to:
$count = $count + 1;
PHP Decrement Operator
The decrement operator -- decreases a variable's value by 1.
Example:
<?php
$count = 5;
$count--;
echo $count;
?>
Output:
4
This:
$count--;
is equivalent to:
$count = $count - 1;
Types of Increment and Decrement Operators
PHP supports four common forms:
| Operator | Name | Description |
|---|---|---|
++$x |
Pre-increment | Increment first, then use the value |
$x++ |
Post-increment | Use the value first, then increment |
--$x |
Pre-decrement | Decrement first, then use the value |
$x-- |
Post-decrement | Use the value first, then decrement |
The distinction becomes important when the operator is used inside an expression.
Pre-Increment Operator
The pre-increment operator is written as:
++$x;
It increments the variable before its value is used in an expression.
Example:
<?php
$x = 5;
$y = ++$x;
echo $x;
echo "\n";
echo $y;
?>
Output:
6
6
The execution is:
$x = 5
↓
$x becomes 6
↓
$y gets 6
So both $x and $y contain 6.
Post-Increment Operator
The post-increment operator is written as:
$x++;
It uses the current value first and increments the variable afterward.
Example:
<?php
$x = 5;
$y = $x++;
echo $x;
echo "\n";
echo $y;
?>
Output:
6
5
The execution is:
$x = 5
↓
$y gets 5
↓
$x becomes 6
Therefore:
$x = 6
$y = 5
Pre-Decrement Operator
The pre-decrement operator is written as:
--$x;
It decreases the value before it is used.
Example:
<?php
$x = 5;
$y = --$x;
echo $x;
echo "\n";
echo $y;
?>
Output:
4
4
The execution is:
$x = 5
↓
$x becomes 4
↓
$y gets 4
Post-Decrement Operator
The post-decrement operator is written as:
$x--;
It uses the current value first and then decreases it.
Example:
<?php
$x = 5;
$y = $x--;
echo $x;
echo "\n";
echo $y;
?>
Output:
4
5
The execution is:
$x = 5
↓
$y gets 5
↓
$x becomes 4
Pre-Increment vs Post-Increment
Consider:
$x = 5;
$y = ++$x;
The value is incremented first:
$x = 6
$y = 6
Now consider:
$x = 5;
$y = $x++;
The value is used first:
$x = 6
$y = 5
The key difference is:
++$x → increment first, then use
$x++ → use first, then increment
Pre-Decrement vs Post-Decrement
Similarly:
$x = 5;
$y = --$x;
produces:
$x = 4
$y = 4
Whereas:
$x = 5;
$y = $x--;
produces:
$x = 4
$y = 5
The rule is:
--$x → decrement first, then use
$x-- → use first, then decrement
Increment Operator in a Loop
Increment operators are commonly used in for loops.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "\n";
}
?>
Output:
1
2
3
4
5
The expression:
$i++
increments $i after each iteration.
Decrement Operator in a Loop
The decrement operator can be used to count backward.
<?php
for ($i = 5; $i >= 1; $i--) {
echo $i . "\n";
}
?>
Output:
5
4
3
2
1
Here:
$i--
decreases $i after each iteration.
Increment with while Loop
Increment operators are also frequently used with while.
<?php
$i = 1;
while ($i <= 5) {
echo $i . "\n";
$i++;
}
?>
Output:
1
2
3
4
5
The counter increases after each iteration.
Decrement with while Loop
Example:
<?php
$i = 5;
while ($i >= 1) {
echo $i . "\n";
$i--;
}
?>
Output:
5
4
3
2
1
Increment in an Expression
The difference between prefix and postfix operators becomes important when they are used inside expressions.
Example:
<?php
$x = 5;
$result = $x++ + 10;
echo $result;
echo "\n";
echo $x;
?>
Output:
15
6
Why?
The post-increment operator uses the original value:
$x = 5
$y = 5 + 10
$x becomes 6
Therefore:
$result = 15
$x = 6
Pre-Increment in an Expression
Now consider:
<?php
$x = 5;
$result = ++$x + 10;
echo $result;
echo "\n";
echo $x;
?>
Output:
16
6
The variable is incremented before its value is used:
$x = 5
↓
$x = 6
↓
$result = 6 + 10
↓
$result = 16
Incrementing by More Than One
The ++ operator increases a value by exactly 1.
For example:
$x++;
is equivalent to:
$x = $x + 1;
If you want to increase by 5, use:
$x += 5;
For example:
<?php
$x = 10;
$x += 5;
echo $x;
?>
Output:
15
Similarly, to decrease by 5:
$x -= 5;
Increment and Decrement with Conditions
Increment and decrement operators can also be used in conditional logic.
Example:
<?php
$count = 0;
while ($count < 3) {
echo "Count: " . $count . "\n";
$count++;
}
?>
Output:
Count: 0
Count: 1
Count: 2
The counter is incremented after each iteration.
Multiple Increment Operations
Consider:
<?php
$x = 5;
$x++;
$x++;
$x++;
echo $x;
?>
Output:
8
Each ++ increases the value by one.
Multiple Decrement Operations
Similarly:
<?php
$x = 5;
$x--;
$x--;
$x--;
echo $x;
?>
Output:
2
Each -- decreases the value by one.
Incrementing a Variable Before Printing
You can use pre-increment when you want the updated value immediately.
<?php
$count = 5;
echo ++$count;
?>
Output:
6
The variable is incremented before echo evaluates its value.
Post-Increment While Printing
With post-increment:
<?php
$count = 5;
echo $count++;
echo "\n";
echo $count;
?>
Output:
5
6
The first echo receives the original value, and the variable is then incremented.
Pre-Decrement While Printing
<?php
$count = 5;
echo --$count;
?>
Output:
4
The value is decremented before it is printed.
Post-Decrement While Printing
<?php
$count = 5;
echo $count--;
echo "\n";
echo $count;
?>
Output:
5
4
The original value is printed first, then the variable is decremented.
Increment and Decrement with Strings
PHP has specific behavior for incrementing strings, particularly strings containing characters. However, decrementing strings does not work as a general-purpose reverse string operation.
For example, numeric strings may behave differently depending on the context and PHP version.
For predictable application code, use numeric variables with ++ and -- when performing numeric counting.
Example:
<?php
$value = 10;
$value++;
echo $value;
?>
Output:
11
For string manipulation, use string-specific operations instead of relying on increment/decrement behavior.
Important Difference Between ++ and += 1
These are commonly equivalent for numeric variables:
$x++;
and:
$x += 1;
For example:
<?php
$x = 10;
$x++;
echo $x;
$x += 1;
echo $x;
?>
Output:
11
12
The main advantage of ++ is concise counter manipulation.
Common Mistakes
Mistake 1: Confusing Prefix and Postfix
Consider:
$x = 5;
$y = $x++;
It is incorrect to assume $y becomes 6.
The actual result is:
$x = 6
$y = 5
For pre-increment:
$x = 5;
$y = ++$x;
the result is:
$x = 6
$y = 6
Mistake 2: Forgetting to Update a Loop Counter
Consider:
$i = 1;
while ($i <= 5) {
echo $i;
}
The value of $i never changes, so the loop does not reach its termination condition.
A counter update is required:
$i++;
Complete example:
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
Mistake 3: Using Complex Expressions
Expressions containing several increment or decrement operations can be difficult to read and maintain.
For example:
$result = $x++ + ++$x;
Although PHP defines expression evaluation behavior, code like this is unnecessarily difficult to understand.
Prefer separate statements:
$x++;
$x++;
$result = $x;
Clear code is generally easier to maintain and debug.
Increment and Decrement Operator Comparison
| Expression | Initial $x |
Final $x |
Value Used |
|---|---|---|---|
++$x |
5 | 6 | 6 |
$x++ |
5 | 6 | 5 |
--$x |
5 | 4 | 4 |
$x-- |
5 | 4 | 5 |
The prefix form changes the value before it is used.
The postfix form changes the value after its current value has been used.
Practical Example: Counting Items
Increment operators are useful for counting.
<?php
$items = 0;
$items++;
$items++;
$items++;
echo "Total items: " . $items;
?>
Output:
Total items: 3
Practical Example: Countdown
A decrement operator can be used to create a countdown.
<?php
$countdown = 5;
while ($countdown > 0) {
echo $countdown . "\n";
$countdown--;
}
echo "Done!";
?>
Output:
5
4
3
2
1
Done!
Key Points to Remember
++increases a variable by1.--decreases a variable by1.++$xis pre-increment.$x++is post-increment.--$xis pre-decrement.$x--is post-decrement.- Prefix operators change the value before it is used.
- Postfix operators use the current value before changing it.
- Increment and decrement operators are commonly used in loops.
$x++is commonly used for forward counters.$x--is commonly used for backward counters.- Use
+=or-=when changing a value by an amount other than1. - Avoid unnecessarily complex expressions containing multiple increment or decrement operations.
Conclusion
PHP's increment and decrement operators provide a concise way to increase or decrease a variable by one.
The four main forms are:
++$x → Pre-increment
$x++ → Post-increment
--$x → Pre-decrement
$x-- → Post-decrement
The most important concept is the difference between prefix and postfix operators:
$y = ++$x;
increments $x before its value is assigned to $y.
$y = $x++;
assigns the current value to $y and increments $x afterward.
Once this distinction is understood, increment and decrement operators become straightforward to use in PHP loops, counters, calculations, and conditional logic.
Related
-
PHP Ternary Operator
Learn how the PHP ternary operator works as a shorthand for conditional statements, including syntax, nested ternary expressions, shorthand syntax, and practical examples.
-
Python Interview Questions and Answers
Prepare for Python interviews with commonly asked questions and answers covering Python basics, data types, functions, OOP, exceptions, collections, modules, and advanced concepts.
-
While Loop
Learn how the while loop in C repeatedly executes a block of code while a condition remains true.