Comma at the end of function arguments in PHP (trailing comma)

Have you ever added a new argument to a function or constructor in PHP and forgotten to add a comma at the end of the previous line? It’s a common mistake that can lead to unnecessary fixes and frustration.

Fortunately, since PHP 7.3 you can use the so-called trailing comma, i.e., a comma after the last argument in function calls, function declarations, and arrays. Thanks to this, when you add a new argument, you don’t have to remember to manually add a comma at the end of the previous line.

🛑 Example without trailing comma

class User {
    public function __construct(
        string $name,
        int $age
    ) {
        // ...
    }
}

If you want to add another argument, you have to go back to the previous line and add a comma:

class User {
    public function __construct(
        string $name,
        int $age, // you have to add a comma
        string $email
    ) {
        // ...
    }
}

✅ Example with trailing comma

class User {
    public function __construct(
        string $name,
        int $age,
    ) {
        // ...
    }
}

Now you can simply add another argument without worrying about commas:

class User {
    public function __construct(
        string $name,
        int $age,
        string $email,
    ) {
        // ...
    }
}

📅 Since when?

Trailing comma in function and method argument lists is available since PHP 7.3. Previously, it was only available in arrays.

📝 Summary

Using the trailing comma:

  • makes adding and removing arguments easier,
  • reduces the risk of syntax errors,
  • improves code readability in the long run.

It’s worth using this feature, especially in larger projects!




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Using array_map() in a Programmer's Daily Life. PHP Review #7
  • Finally well written tests with composer loading structure
  • How integrate GitHub Copilot to generate commit messages automatically?
  • 🤓 Why do PHP developers love the empty line at the end of the file? PHP Review #6
  • 🧹 How to Remove Recipes from the `extra` Section in composer.json