Detect unnecessary 'use' statements with PHP CodeSniffer

Aug 26, 2021 by Thibault Debatty | 4705 views

PHP Secure Software Development

PHP Code Sniffer is a great tool to make sure your code is nicely written. Next to the default rules, you can also install and use additional rules (sniffs) to further enhance your code. Is here how to use PHPCS to detect (and remove) all unnecessary 'use' statements in your code.


Install PHPCS

If you don't have PHPCS yet, you should first install:

composer require --dev squizlabs/php_codesniffer

Then create a configuration file called phpcs.xml:

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>The coding standard for our project.</description>

    <!-- the standard that should be used -->
    <rule ref="PSR2"/>

    <!-- directories to check -->

This configuration will check that the code in directories app and tests is written according to the PSR2 standard.

You can now run PHPCS (and check that your configuration is correct) with:


If you are using Laravel, you can find a typical configuration here:

Install Slevomat Coding Standard

Slevomat Coding Standard provides additional rules (sniffs), to help further improve your code. You can find the full list of sniffs at

Installation is done with composer (as usual):

composer require --dev slevomat/coding-standard

Then you can add the sniffs to your phpcs.xml:

<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
    <description>The coding standard for our project.</description>
    <rule ref="PSR2"/>

    <!-- lines omitted for brevity -->

    <!-- Add rules from slevomat -->
    <config name="installed_paths" value="../../slevomat/coding-standard"/>
    <rule ref="SlevomatCodingStandard.Namespaces.UnusedUses"/>


You can now run PHPCS with all the sniffs as usual:


Going further

Once you have detected (and removed) all unnecessary 'use' statements from your code, you can also remove all unused composer dependencies.

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.