PHP Formatter

Fix the indentation of PHP code. Blocks, arrays, and switch statements are re-indented, while strings, heredocs, comments, and inline HTML are left alone.

Updated
Runs in your browser. Your data is not uploaded.
Formats as you type for inputs up to 200 KB.

How to use the PHP Formatter

  1. Paste PHP into PHP input, or upload or drop a .php file.
  2. Pick the Indent. PSR-12, the common PHP style standard, uses 4 spaces.
  3. Press Format, then copy the result or download it.

How it works

The formatter is deliberately conservative. It reads the code as PHP tokens and changes only the whitespace at the start and end of each line.

  • Each {, (, or [ left open at the end of a line indents the following lines by one level, and the matching closer brings them back.
  • Inside a switch, the body of each case and default is indented one level below it.
  • Lines inside multi-line strings, heredoc and nowdoc blocks, and /* ... */ comments are copied unchanged, because their whitespace is part of the content.
  • Text outside <?php ... ?> is HTML and is kept as written.
  • Trailing spaces are removed, and a line break is added at the end of the file.

Examples

Input:

<?php
function total(array $items): float {
$sum = 0;
foreach ($items as $item) {
switch ($item['type']) {
case 'book':
$sum += $item['price'] * 0.9;
break;
default:
$sum += $item['price'];
}
}
return $sum;
}

Formatted with 4 spaces:

<?php
function total(array $items): float {
    $sum = 0;
    foreach ($items as $item) {
        switch ($item['type']) {
            case 'book':
                $sum += $item['price'] * 0.9;
                break;
            default:
                $sum += $item['price'];
        }
    }
    return $sum;
}

Limitations

  • Only indentation changes. Spacing around operators, line length, brace placement, and blank lines stay as written. For a full PSR-12 rewrite, run PHP-CS-Fixer or PHP_CodeSniffer in your project.
  • Code that puts several statements or blocks on one line keeps them on one line.
  • Statements without braces, such as if ($a) foo(); split over two lines, are not indented.
  • The code isn't run or checked for errors. Files are limited to 5 MB.

Frequently asked questions

Does this formatter follow PSR-12?

It uses PSR-12's 4-space indentation and case indentation, but it doesn't rewrite braces, spacing, or line length. Use PHP-CS-Fixer for full PSR-12 formatting.

Will it change my strings or heredocs?

No. Lines inside strings, heredoc, nowdoc, and block comments are kept exactly as they are, because changing their indentation would change your data.

Can I format a Blade or WordPress template?

Yes. HTML outside PHP tags is left alone, and the PHP inside the tags is indented. Blade directives such as @if are treated as HTML.

Is my code uploaded?

No. It is formatted in your browser.

Often used together with the PHP Formatter.