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
🌐
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.

🌐
GitHub
github.com › lkrms › pretty-php
GitHub - lkrms/pretty-php: The opinionated PHP code formatter
Previous formatting is ignored, and nothing other than whitespace is changed (see Pragmatism for exceptions) ... PHP 8.4, 8.3, 8.2, 8.1, 8.0 or 7.4 with the standard tokenizer, mbstring and json extensions enabled · pretty-php is distributed as a PHP archive you can download and run: wget -O pretty-php.phar https://github.com/lkrms/pretty-php/releases/latest/download/pretty-php.phar ... wget -O pretty-php.phar https://github.com/lkrms/pretty-php/releases/latest/download/pretty-php.phar wget -O pretty-php.phar.asc https://github.com/lkrms/pretty-php/releases/latest/download/pretty-php.phar.asc gpg --recv-keys 0xE8CC5BC780B581F2 gpg --verify pretty-php.phar.asc pretty-php.phar
Starred by 146 users
Forked by 3 users
Languages   PHP 98.3% | Shell 1.5% | Latte 0.2%
People also ask

What does a PHP Formatter do?
A PHP Formatter analyzes your PHP script and automatically applies consistent formatting rules for indentation, spacing, line breaks, brace style, and more, based on standards like PSR-12 or Prettier's defaults. It makes messy or inconsistently styled code clean and readable without changing its logic.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
Is this online PHP formatter free?
Yes, this tool is completely free to use online without any usage restrictions or mandatory sign-up.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
Does this tool fix bugs or errors in my PHP code?
No. This is a code formatter, not a debugger or static analyzer (linter). It focuses on code style and structure. While it might fail on severe syntax errors, it won't find logical errors, security vulnerabilities, or runtime issues in your PHP script.
🌐
codeshack.io
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
🌐
BeautifyTools
beautifytools.com › php-beautifier.php
Online PHP Beautifier - PHP Formatter - BeautifyTools.com
Beautify dirty, ugly PHP code using Online PHP Beautifier and make your PHP code more readable. It gives the PHP code proper indentation with spaces or tabs.
🌐
Duplichecker.com
duplichecker.com › php-formatter
PHP Formatter - Beautify Your Messy PHP Code Online
The PHP code formatter offered by the DupliChecker is the best option that you could find over the web for beautifying your PHP.
🌐
GitHub
github.com › prettier › plugin-php
GitHub - prettier/plugin-php: Prettier PHP Plugin · GitHub
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary. This plugin adds support for the PHP language to Prettier.
Author   prettier
🌐
CodeShack
codeshack.io › home › tools › php formatter
PHP Formatter - Beautify and Format PHP Code Online
This tool uses the powerful Prettier library and its PHP plugin directly in your browser, keeping your code private and secure. A PHP Formatter analyzes your PHP script and automatically applies consistent formatting rules for indentation, spacing, line breaks, brace style, and more, based on standards like PSR-12 or Prettier's defaults.
🌐
PHPHub
phphub.net › home › php formatter
PHP beautifier
April 12, 2024 - Easily and swiftly format your PHP code with this online PHP code formatter. Ensure effortless readability and code quality.
Find elsewhere
🌐
Code Beautify
codebeautify.org › php-beautifier
PHP Beautifier and PHP Formatter Online
PHP Source Code Beautifier Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.
Top answer
1 of 14
104

Update 2021-07-21

It's been more than half a decade since I first wrote this answer. The extensions to which I originally linked are abandoned, and Visual Studio Code's intrinsic PHP support hasn't improved, which is disappointing. The only decent extension still standing of which I'm aware is PHP Intelephense, which uses a freemium model: basic features are free, and a lifetime license is $12 USD as of writing.

The free version of Intelephense supports code formatting with the usual shortcuts (Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.

Original answer

Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.

They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you're on Mac, give ⌥⇧F a try.

2 of 14
51

I installed

  • Prettier for HTML, CSS, and JavaScript files

  • PHP Intelephense for PHP files

I followed the instructions for each plugin but found I had to additionally edit settings.json manually in order to get them to work together.

"editor.defaultFormatter": "esbenp.prettier-vscode",
"[php]": {
  "editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
}

The settings use Intelephense as the formatter for PHP files and use Prettier as the formatter for all other files.

Now I use Shift + Alt + F to format the files like everybody else.

🌐
GoOnlineTools.com
goonlinetools.com › php-beautifier
PHP Beautifier - Best PHP Formatter | GoOnlineTools
This Best free online PHP Beautifier Beautify ugly, minified PHP code and give it proper indentation to make it more readable.
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.

🌐
TutorialsPoint
tutorialspoint.com › online_php_formatter.htm
Online PHP Formatter | Tutorialspoint
Online PHP Formatter and Beautifier - Try online PHP Code formatter and beautifier and Editor to beautify and format PHP code using jQuery Plug-in
🌐
JSON Formatter
jsonformatter.org › php-formatter
PHP Formatter and PHP Beautifier free and easy to Format PHP Code Online
This PHP Formatter online tool is very powerful. PHP stands for Hypertext Preprocessor and it's scripting language that is especially suited to web development. Danish-Canadian programmer Rasmus Lerdorf has developed PHP in 1994. PHP is Fast, flexible and pragmatic, and powers everything from blog to the most popular websites in the world. Use this icon to restore the last PHP code from the browser's local storage. ... Best and Secure online PHP Formatter work well in Windows, Mac, Linux, Chrome, Firefox, Safari, and Edge.
🌐
Phpformatter
phpformatter.com
PHP Formatter – A Unique Blog about PHP
This allows you to understand the code that you have written defining and given meaning… ... The array_chunk() function on the on the other hand as the name implies, divides an array into chunks or several tables from the source table. The syntax goes something… ... There are different categories of an error message that the PHP ...
🌐
Encode64
encode64.com › home › formatters › php formatter
Free Online PHP Beautifier – Clean & Format PHP Code Instantly | Encode64
The tool auto-detects PHP syntax and prepares it for formatting. ... Choose your indent size, whether to use spaces or tabs, and the preferred wrap / line length. Defaults are sensible for most PSR-12–style projects. ... Hit **Format** to run your code through Prettier’s PHP engine.
🌐
GeeksforGeeks
geeksforgeeks.org › utilities › php-formatter
Online PHP Formatter and PHP Beautifier (Free & Easy to Use) - GeeksforGeeks
January 2, 2024 - Integrates into various IDEs and code editors, providing real-time or batch formatting for efficient codebase management. Code Analysis : The PHP Formatter analyzes your PHP code input.
🌐
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!
🌐
Visual Studio Marketplace
marketplace.visualstudio.com › items
PHP Formatter - Visual Studio Marketplace
Extension for Visual Studio Code - A wrapper for the Sensiolabs PHP CS Fixer. Analyzes some PHP source code and tries to fix coding standards issues (PSR-1 and PSR-2 compatible).
🌐
GitHub
github.com › phpowermove › php-code-formatter
GitHub - phpowermove/php-code-formatter: A code formatting library for php
use gossi\formatter\Formatter; $formatter = new Formatter(); $beautifulCode = $formatter->format($uglyCode); ... php code formatter is not yet finished (see Wishlist). Please help the development, by picking one of the open issues or implement ...
Starred by 31 users
Forked by 11 users
Languages   PHP
🌐
Wtools
wtools.io › php-formatter
Online PHP Formatter, PHP Beautifier | WTOOLS
Just paste your PHP code to the textarea above and click to the button "Formatter" and you will get formatted PHP in the same textarea. ... Did you like this tool? You can donate to us. This will help us improve our free web tools. Paypal ... Do you like cookies? 🍪 We use cookies to ensure you get the best ...