What is Trailing Comma in PHP?

PHPServer Side ProgrammingProgramming

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

function($x,$y,$z){
}

In PHP 8.0

In PHP 8, we can add trailing commas at the end of the last parameter. PHP 8 allows using the trailing commas in the parameter list and Closure use list.

Example

function($x,$y,$z,){}

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"
raja
Published on 01-Apr-2021 06:37:28
Advertisements