Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is Trailing Comma in PHP?
Trailing commas in PHP allow you to add a comma after the last element in arrays, function parameters, and function calls. This feature was introduced in PHP 7.2 for arrays and expanded in PHP 8.0 for function parameters and calls.
Benefits of Trailing Commas
Trailing commas make code more maintainable by allowing you to add new elements without modifying existing lines. This reduces merge conflicts in version control and makes code changes cleaner.
Arrays (PHP 7.2+)
You can use trailing commas in arrays since PHP 7.2 −
<?php
$fruits = [
'apple',
'banana',
'orange',
];
print_r($fruits);
?>
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Function Parameters (PHP 8.0+)
PHP 8.0 allows trailing commas in function parameter lists −
<?php
function employeeAdd(
string $country,
string $city,
string $street,
) {
return $country . ', ' . $city . ', ' . $street;
}
$result = employeeAdd('India', 'Bangalore', 'Indira Nagar');
echo $result;
?>
India, Bangalore, Indira Nagar
Function Calls (PHP 8.0+)
Trailing commas are also allowed in function calls −
<?php
function addNumbers($x, $y, $z) {
return $x + $y + $z;
}
$result = addNumbers(
10,
20,
30,
);
echo "Sum: " . $result;
?>
Sum: 60
Comparison
| Feature | PHP Version | Supported |
|---|---|---|
| Arrays | 7.2+ | Yes |
| Function Parameters | 8.0+ | Yes |
| Function Calls | 8.0+ | Yes |
Conclusion
Trailing commas improve code maintainability by reducing the need to modify existing lines when adding new elements. They are supported in arrays since PHP 7.2 and in function parameters and calls since PHP 8.0.
