What is Trailing Comma in PHP?

PHPServer Side ProgrammingProgramming

Kickstart HTML, CSS and PHP: Build a Responsive Website

Featured

59 Lectures 8.5 hours

Trailing commas are being used in PHP since PHP 7.2 version. We can use trailing commas in the last item in the array. We can add the element of the array without modifying the last line of the item if the line is already using a trailing comma.

Trailing Commas before PHP 8.0

Before PHP 8, we were not able add a comma to the end of the last parameter.

Example: Using Trailing Comma in PHP in function, method, and closure calls.

<?php
function EmployeeAdd(string $country, string$city, string $street): string { return$country . ', ' . $city. ', ' .$street;
}
$result = employeeAdd( 'India', 'Bangalore', 'Indira Nagar', ); print_r($result);
?>

Output

India, Bangalore, Indira Nagar

Example: Trailing Comma PHP 8 with multiple arguments

<?php
function method_with_many_arguments(
$x,$y,
\$z,
)
{
var_dump("shows valid syntax");
}
method_with_many_arguments(
1,
2,
3,
4,
);
?>

Output

string(18) "shows valid syntax"
Updated on 01-Apr-2021 06:41:46