php-cs-fixer https://github.com/PHP-CS-Fixer/PHP-CS-Fixer I do disagree on code standards being enforced in the IDE. My view is they absolutely need to be enforced at the project level to ensure consistency of code standard throughout that project. The IDE should be capable of configuring itself based on project owned configurations (this is the case when using php-cs-fixer). Edit: To your point of having an opinionated standard set out of the box. PSR12 https://www.php-fig.org/psr/psr-12/ . A rulset for this standard already exists in php-cs-fixer. Edit 2: For absolute transparency, there is also another popular capable of doing everything I mentioned above - https://github.com/squizlabs/PHP_CodeSniffer Answer from JParkinson1991 on reddit.com
🌐
Phpqa
phpqa.io › projects › phpcbf.html
PHP Code Beautifier and Fixer | PHP Quality Assurance
PHP Code Beautifier and Fixer is part of a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations.
🌐
GitHub
github.com › squizlabs › PHP_CodeSniffer › wiki › Fixing-Errors-Automatically
Fixing Errors Automatically · squizlabs/PHP_CodeSniffer Wiki · GitHub
PHP_CodeSniffer is able to fix many errors and warnings automatically. The diff report can be used to generate a diff that can be applied using the patch command. Alternatively, the PHP Code Beautifier and Fixer (phpcbf) can be used in place ...
Author   squizlabs
🌐
Code Beautify
codebeautify.org › php-beautifier
PHP Beautifier and PHP Formatter Online
PHP Beautifier online helps to format and indent the php source code and help to share with others.
🌐
GitHub
github.com › PHPCSStandards › PHP_CodeSniffer › wiki › Fixing-Errors-Automatically
Fixing Errors Automatically · PHPCSStandards/PHP_CodeSniffer Wiki · GitHub
PHP_CodeSniffer is able to fix many errors and warnings automatically. The PHP Code Beautifier and Fixer (phpcbf) can be used instead of phpcs to automatically generate and apply the fixes for you.
Author   PHPCSStandards
🌐
LinkedIn
linkedin.com › all › engineering › web applications
How can PHP Code Beautifier and Fixer improve your PHP code readability?
January 17, 2024 - Learn how to use PHP Code Beautifier and Fixer (PHP CS Fixer) to format and fix your PHP code automatically and improve your web applications.
🌐
GitHub
github.com › soderlind › vscode-phpcbf
GitHub - soderlind/vscode-phpcbf: PHP Code Beautifier and Fixer for Visual Studio Code
This extension provides the PHP Code Beautifier and Fixer (phpcbf) command for Visual Studio Code.
Starred by 28 users
Forked by 10 users
Languages   JavaScript 100.0% | JavaScript 100.0%
🌐
Reddit
reddit.com › r/phphelp › what is the most common php code formatter?
r/PHPhelp on Reddit: What is the most common PHP code formatter?
August 1, 2024 -

I found three code formatters for PHP.

  • Prettier (With PHP Plugin)

  • PrettyPHP (https://github.com/lkrms/vscode-pretty-php)

  • phpfmt (https://github.com/kokororin/vscode-phpfmt)

I was able to setup Prettier with the PHP plugin but the setup is not ideal since I have to install prettier and the prettier PHP plugin from NPM into the project every single time which is not the case when using Prettier VSCode extension with HTML, JS and CSS. I do like how Prettier has its own configuration .prettierrc files and it allows you to set a standard format for a project you are collaborating with others, however I believe formatting should be done in the IDE such as using a VSCode extension and this is the case with the Prettier extension for HTML, JS and CSS but not for PHP since it requires NPM packages.

The other two do not look popular. Am I missing something? I would like to have a standard format or be able to have an opinionated format setup like Prettier for JS but for PHP.

Find elsewhere
🌐
GitHub
gist.github.com › soderlind › 33eca92ffd22420681518e4abaef1849
VS Code: PHP Code Beautifier and Fixer (phpcbf) and Short Array Syntax Converter task runners. · GitHub
Add the content in tasks.json to ./.vscode/tasks.json. Make sure the paths are correct. When you want to beautify PHP, or convert array() to [], on a Mac, hit Shift+Cmd+B and select the task runner.
🌐
BeautifyTools
beautifytools.com › php-beautifier.php
Online PHP Beautifier - PHP Formatter - BeautifyTools.com
Online PHP Beautifier, PHP Formatter beautifies dirty, ugly or unreadable PHP code and give it proper indentation. It supports various indentation styles such as K&R style, Allman style, Whitesmiths style and GNU style.
🌐
Encode64
encode64.com › home › beautifiers › php beautifier
Free Online PHP Beautifier – Format & Clean Your PHP Code Instantly | Encode64
Beautify and auto-format PHP code online with full PSR-12 and Symfony coding standards. Clean up, fix style issues, and optimize readability in seconds. Fast, secure, and 100% free.
🌐
Unibeautify
unibeautify.com › docs › beautifier-php-cs-fixer
PHP-CS-Fixer Beautifier · Unibeautify
PHP-CS-Fixer executable should ... are non-Node.js tools for code formatting while beautifiers are Node.js packages which wrap an executable to be used by Unibeautify. PHP-CS-Fixer executable is a third-party program you must install manually ...
🌐
Visual Studio Marketplace
marketplace.visualstudio.com › items
PHP Sniffer & Beautifier for VS Code
Extension for Visual Studio Code - PHP Sniffer & Beautifier for Visual Studio Code
🌐
CodeShack
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
Format and beautify your PHP code online according to PSR standards. Paste messy PHP or load a file, choose indentation and PHP version, and get clean code.
Top answer
1 of 14
43

Well here is my very basic and rough script:

#!/usr/bin/php
<?php
class Token {
    public $type;
    public $contents;

    public function __construct($rawToken) {
        if (is_array($rawToken)) {
            $this->type = $rawToken[0];
            $this->contents = $rawToken[1];
        } else {
            $this->type = -1;
            $this->contents = $rawToken;
        }
    }
}

$file = $argv[1];
$code = file_get_contents($file);

$rawTokens = token_get_all($code);
$tokens = array();
foreach ($rawTokens as $rawToken) {
    $tokens[] = new Token($rawToken);
}

function skipWhitespace(&$tokens, &$i) {
    global $lineNo;
    $i++;
    $token = $tokens[$i];
    while ($token->type == T_WHITESPACE) {
        $lineNo += substr($token->contents, "\n");
        $i++;
        $token = $tokens[$i];
    }
}

function nextToken(&$j) {
    global $tokens, $i;
    $j = $i;
    do {
        $j++;
        $token = $tokens[$j];
    } while ($token->type == T_WHITESPACE);
    return $token;
}

$OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&&', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '<=', '>=', '<', '>', '===', '!==');

$IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE);

$CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE);
$WHITESPACE_BEFORE = array('?', '{', '=>');
$WHITESPACE_AFTER = array(',', '?', '=>');

foreach ($OPERATORS as $op) {
    $WHITESPACE_BEFORE[] = $op;
    $WHITESPACE_AFTER[] = $op;
}

$matchingTernary = false;

// First pass - filter out unwanted tokens
$filteredTokens = array();
for ($i = 0, $n = count($tokens); $i < $n; $i++) {
    $token = $tokens[$i];
    if ($token->contents == '?') {
        $matchingTernary = true;
    }
    if (in_array($token->type, $IMPORT_STATEMENTS) && nextToken($j)->contents == '(') {
        $filteredTokens[] = $token;
        if ($tokens[$i + 1]->type != T_WHITESPACE) {
            $filteredTokens[] = new Token(array(T_WHITESPACE, ' '));
        }
        $i = $j;
        do {
            $i++;
            $token = $tokens[$i];
            if ($token->contents != ')') {
                $filteredTokens[] = $token;
            }
        } while ($token->contents != ')');
    } elseif ($token->type == T_ELSE && nextToken($j)->type == T_IF) {
        $i = $j;
        $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif'));
    } elseif ($token->contents == ':') {
        if ($matchingTernary) {
            $matchingTernary = false;
        } elseif ($tokens[$i - 1]->type == T_WHITESPACE) {
            array_pop($filteredTokens); // Remove whitespace before
        }
        $filteredTokens[] = $token;
    } else {
        $filteredTokens[] = $token;
    }
}
$tokens = $filteredTokens;

function isAssocArrayVariable($offset = 0) {
    global $tokens, $i;
    $j = $i + $offset;
    return $tokens[$j]->type == T_VARIABLE &&
        $tokens[$j + 1]->contents == '[' &&
        $tokens[$j + 2]->type == T_STRING &&
        preg_match('/[a-z_]+/', $tokens[$j + 2]->contents) &&
        $tokens[$j + 3]->contents == ']';
}

// Second pass - add whitespace
$matchingTernary = false;
$doubleQuote = false;
for ($i = 0, $n = count($tokens); $i < $n; $i++) {
    $token = $tokens[$i];
    if ($token->contents == '?') {
        $matchingTernary = true;
    }
    if ($token->contents == '"' && isAssocArrayVariable(1) && $tokens[$i + 5]->contents == '"') {
        /*
         * Handle case where the only thing quoted is the assoc array variable.
         * Eg. "$value[key]"
         */
        $quote = $tokens[$i++]->contents;
        $var = $tokens[$i++]->contents;
        $openSquareBracket = $tokens[$i++]->contents;
        $str = $tokens[$i++]->contents;
        $closeSquareBracket = $tokens[$i++]->contents;
        $quote = $tokens[$i]->contents;        
        echo $var . "['" . $str . "']";
        $doubleQuote = false;
        continue;
    }
    if ($token->contents == '"') {
        $doubleQuote = !$doubleQuote;
    }
    if ($doubleQuote && $token->contents == '"' && isAssocArrayVariable(1)) {
        // don't echo "
    } elseif ($doubleQuote && isAssocArrayVariable()) {
        if ($tokens[$i - 1]->contents != '"') {
            echo '" . ';
        }
        $var = $token->contents;
        $openSquareBracket = $tokens[++$i]->contents;
        $str = $tokens[++$i]->contents;
        $closeSquareBracket = $tokens[++$i]->contents;
        echo $var . "['" . $str . "']";
        if ($tokens[$i + 1]->contents != '"') {
            echo ' . "';
        } else {
            $i++; // process "
            $doubleQuote = false;
        }
    } elseif ($token->type == T_STRING && $tokens[$i - 1]->contents == '[' && $tokens[$i + 1]->contents == ']') {
        if (preg_match('/[a-z_]+/', $token->contents)) {
            echo "'" . $token->contents . "'";
        } else {
            echo $token->contents;
        }
    } elseif ($token->type == T_ENCAPSED_AND_WHITESPACE || $token->type == T_STRING) {
        echo $token->contents;
    } elseif ($token->contents == '-' && in_array($tokens[$i + 1]->type, array(T_LNUMBER, T_DNUMBER))) {
        echo '-';
    } elseif (in_array($token->type, $CONTROL_STRUCTURES)) {
        echo $token->contents;
        if ($tokens[$i + 1]->type != T_WHITESPACE) {
            echo ' ';
        }
    } elseif ($token->contents == '}' && in_array($tokens[$i + 1]->type, $CONTROL_STRUCTURES)) {
        echo '} ';
    } elseif ($token->contents == '=' && $tokens[$i + 1]->contents == '&') {
        if ($tokens[$i - 1]->type != T_WHITESPACE) {
            echo ' ';
        }
        $i++; // match &
        echo '=&';
        if ($tokens[$i + 1]->type != T_WHITESPACE) {
            echo ' ';          
        }
    } elseif ($token->contents == ':' && $matchingTernary) {
        $matchingTernary = false;
        if ($tokens[$i - 1]->type != T_WHITESPACE) {
            echo ' ';
        }
        echo ':';
        if ($tokens[$i + 1]->type != T_WHITESPACE) {
            echo ' ';
        }
    } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE &&
        in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {
        echo ' ' . $token->contents . ' ';
    } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE) {
        echo ' ' . $token->contents;
    } elseif (in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {
        echo $token->contents . ' ';
    } else {
        echo $token->contents;
    }
}
2 of 14
15

http://en.sourceforge.jp/projects/pdt-tools/

^^^ will give you a proper CTRL+SHIFT+F Eclipse/Aptana PHP formatter like Java.

See here for installation help.

🌐
Encode64
encode64.com › home › formatters › php formatter
Free Online PHP Beautifier – Clean & Format PHP Code Instantly | Encode64
Online PHP formatter powered by Prettier and the official PHP plugin. Paste or upload PHP files and get clean, PSR-12–aligned code with consistent indentation and spacing. Ideal for Laravel, Symfony, WordPress and modern PHP 8 projects.
🌐
Testmu
testmu.ai › home › free tools › php formatter & beautifier online
PHP Formatter & Beautifier Online | TestMu AI
Struggling with messy PHP Formatter & Beautifier Online scripts? Our PHP Formatter & Beautifier Online tool provides clean and structured formatting. Beautify your code and Improve readability today!
🌐
Symfony
cs.symfony.com
PHP Coding Standards Fixer
The PHP Coding Standards Fixer (PHP CS Fixer) fixes your code to follow the standards.