🐘

PHP Beautifier

Format and beautify PHP code following PSR-12 coding standards with proper indentation, spacing, and line breaks. Perfect for cleaning up messy code or enforcing consistent style.

Developer ToolsUtility
Loading tool...

How to Use PHP Beautifier

Quick Start Guide

  1. Paste Code: Copy your messy PHP code into the input area
  2. Configure Options: Choose indent size, brace style, and spacing preferences
  3. Beautify: Click "Beautify Code" to format your PHP
  4. Copy or Download: Use the output buttons to copy or download the formatted code
  5. Try Examples: Click example buttons to see different PHP formatting scenarios

What is PHP Beautification?

PHP beautification (also called formatting or pretty-printing) transforms messy, inconsistent, or poorly formatted PHP code into clean, PSR-12 compliant code with proper indentation, spacing, and line breaks.

Purpose: Code readability, PSR-12 compliance, team consistency Input: Messy, inconsistent, or unformatted PHP code Output: Clean, PSR-12 compliant, readable PHP code Usage: Development, code review, maintaining standards

Why Beautify PHP Code?

Development Benefits:

  • Enforce PSR-12 coding standards automatically
  • Standardize code style across your team
  • Make code reviews faster and more effective
  • Improve code readability and maintainability
  • Clean up code from online sources or tutorials
  • Learn PHP best practices through examples

Common Scenarios:

  • Formatting code from Stack Overflow or tutorials
  • Cleaning up legacy PHP codebases
  • Enforcing team coding standards
  • Preparing code for code reviews
  • Standardizing Laravel, Symfony, or WordPress code
  • Migrating from older PHP coding styles

PSR-12 Coding Standard

PSR-12 (PHP Standard Recommendation 12) is the extended coding style guide for PHP. Key points:

Indentation:

  • Use 4 spaces per indentation level (not tabs)
  • Continuation lines should align wrapped elements

Braces:

  • Opening braces for classes go on the next line
  • Opening braces for methods go on the next line
  • Opening braces for control structures go on the same line

Spacing:

  • Space after control structure keywords (if, while, for)
  • No space after function name before parentheses
  • Space around operators (=, +, -, *, /, etc.)
  • Space after commas in argument lists

Naming:

  • Classes: PascalCase (UserController)
  • Methods: camelCase (getUserById)
  • Constants: UPPERCASE_WITH_UNDERSCORES

Formatting Options Explained

Indent Size

4 spaces (PSR-12 standard):

  • Official PHP standard
  • Most widely used in PHP community
  • Required for PSR-12 compliance

2 spaces:

  • More compact, saves vertical space
  • Less common in PHP
  • Not PSR-12 compliant

When to use:

  • 4 spaces: Always (PSR-12 standard)
  • 2 spaces: Only if team specifically requires it

Braces on New Line

Off (PSR-12 for control structures):

if ($condition) {
    // code
}

On (Allman style):

if ($condition)
{
    // code
}

Recommendation: Off for control structures (PSR-12 standard)

Space After Keywords

Enabled (PSR-12):

if ($x) { }
while ($y) { }
foreach ($items as $item) { }

Disabled:

if($x) { }
while($y) { }
foreach($items as $item) { }

Recommendation: Always enable (PSR-12 requirement)

Common Use Cases

1. Formatting Classes and Methods

Purpose: Clean up class definitions and method signatures

Before:

<?php
class UserController{private $db;
public function __construct($database){
$this->db=$database;}
public function getUser($id){
$user=$this->db->query("SELECT * FROM users WHERE id = ?",[$id]);
return $user;}}

After (formatted with 4-space indent):

<?php
class UserController
{
    private $db;

    public function __construct($database)
    {
        $this->db = $database;
    }

    public function getUser($id)
    {
        $user = $this->db->query(
            "SELECT * FROM users WHERE id = ?",
            [$id]
        );
        return $user;
    }
}

2. Formatting Arrays and Loops

Purpose: Make arrays and control structures readable

Before:

<?php
$numbers=[1,2,3,4,5];$squared=array_map(function($n){return $n*$n;},$numbers);foreach($numbers as $num){if($num%2===0){echo $num.' even';}else{echo $num.' odd';}}

After:

<?php
$numbers = [1, 2, 3, 4, 5];

$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);

foreach ($numbers as $num) {
    if ($num % 2 === 0) {
        echo $num . ' even';
    } else {
        echo $num . ' odd';
    }
}

3. Formatting Namespaces and Use Statements

Purpose: Clean up namespace declarations and imports

Before:

<?php
namespace App\\Controllers;use App\\Models\\User;use App\\Services\\AuthService;use Illuminate\\Http\\Request;class UserController{private $authService;public function __construct(AuthService $authService){$this->authService=$authService;}}

After:

<?php
namespace App\\Controllers;

use App\\Models\\User;
use App\\Services\\AuthService;
use Illuminate\\Http\\Request;

class UserController
{
    private $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }
}

4. Formatting Exception Handling

Purpose: Make try-catch blocks readable

Before:

<?php
function connectDatabase($host,$db){try{$pdo=new PDO("mysql:host=$host;dbname=$db");return $pdo;}catch(PDOException $e){error_log('Connection failed: '.$e->getMessage());return null;}finally{echo 'Complete';}}

After:

<?php
function connectDatabase($host, $db)
{
    try {
        $pdo = new PDO(
            "mysql:host=$host;dbname=$db"
        );
        return $pdo;
    } catch (PDOException $e) {
        error_log(
            'Connection failed: ' . $e->getMessage()
        );
        return null;
    } finally {
        echo 'Complete';
    }
}

Features

Core Functionality

  • PSR-12 Compliance: Format code following PHP standards
  • Automatic Indentation: Proper 4-space indentation
  • Whitespace Normalization: Correct spacing around operators
  • Line Break Management: Insert breaks for readability
  • Comment Preservation: Keep all comments intact
  • String Safety: Never modify string contents

Supported PHP Features

Basic Syntax:

  • Function definitions
  • Class definitions
  • Conditional statements (if, elseif, else)
  • Loops (for, foreach, while)
  • Exception handling (try, catch, finally)

OOP Features:

  • Classes and methods
  • Visibility modifiers (public, private, protected)
  • Namespaces and use statements
  • Interfaces and traits
  • Abstract classes

Modern PHP:

  • Type declarations
  • Return types
  • Nullable types
  • Anonymous functions
  • Arrow functions (PHP 7.4+)

Formatting Controls

Indent Size:

  • 2 spaces (compact)
  • 4 spaces (PSR-12 standard)

Braces on New Line:

  • Off (PSR-12 for control structures)
  • On (Allman style)

Space After Keywords:

  • Enabled (PSR-12 standard)
  • Disabled (compact style)

Best Practices

1. Follow PSR-12

Recommended settings:

  • Indent: 4 spaces
  • Braces: On new line for classes/methods
  • Space after keywords: Enabled

2. Format Before Committing

Workflow:

  1. Write your PHP code
  2. Format before committing
  3. Run PHP CodeSniffer for validation
  4. Run tests
  5. Commit formatted code

3. Combine with Linters

Recommended tools:

  • PHP-CS-Fixer: Automatic PSR-12 formatting
  • PHP_CodeSniffer: Style checking and validation
  • PHPStan: Static analysis
  • Psalm: Type checking

4. Set Up Pre-commit Hooks

# .git/hooks/pre-commit
#!/bin/bash
vendor/bin/php-cs-fixer fix --dry-run --diff

5. Document Your Style

For teams:

  • Document preferred formatting settings
  • Add to project README
  • Create .editorconfig file
  • Use composer scripts for formatting

Technical Details

How PHP Beautification Works

1. Parse PHP code character by character
2. Track context (strings, comments, PHP tags)
3. Identify blocks (functions, classes, control structures)
4. Apply proper indentation (4 spaces per level)
5. Add spacing around operators and keywords
6. Insert blank lines between class members
7. Output PSR-12 compliant code

Limitations

This is a basic beautifier:

  • Uses character-based parsing (not full AST)
  • May not handle all edge cases
  • Works well for common PHP patterns
  • Not a replacement for PHP-CS-Fixer

For production, consider:

  • PHP-CS-Fixer: Full PSR-12 compliance, extensive rules
  • PHP_CodeSniffer: Detection and fixing of violations
  • PHP-CS-Fixer in CI/CD: Automated formatting checks

This tool is best for:

  • Quick one-off formatting
  • Learning PHP style
  • Formatting code snippets
  • Simple formatting tasks
  • Privacy-focused use (100% local)

Browser Compatibility

Supported browsers:

  • βœ… Chrome 90+
  • βœ… Firefox 88+
  • βœ… Safari 14+
  • βœ… Edge 90+
  • βœ… Opera 76+

Works on:

  • Desktop: Windows, macOS, Linux
  • Mobile: iOS Safari, Chrome Android
  • Tablets: iPad, Android tablets

Privacy & Security

Client-Side Processing

  • 100% Local: All formatting in your browser
  • No Uploads: Code never sent to server
  • No Storage: Nothing saved or cached
  • No Tracking: No analytics on code
  • No Accounts: No login required

Safe for Sensitive Code

  • βœ… Proprietary PHP code
  • βœ… Client projects
  • βœ… Production code
  • βœ… Code with business logic
  • βœ… Personal projects

Important: Remove database credentials, API keys, and secrets before sharing code.

Comparison with Other Tools

PHP Beautifier vs PHP-CS-Fixer

This Tool:

  • βœ… Browser-based, instant
  • βœ… Simple options
  • βœ… No installation
  • βœ… Privacy-focused (100% local)
  • ❌ Basic parsing
  • ❌ Limited PSR-12 coverage

PHP-CS-Fixer:

  • βœ… Full PSR-12 compliance
  • βœ… Extensive rule set
  • βœ… AST-based parsing
  • βœ… Production-ready
  • ❌ Requires Composer
  • ❌ Command-line setup needed

When to use this tool: Quick formatting, learning, one-off tasks

When to use PHP-CS-Fixer: Production projects, team collaboration, CI/CD

Integration Tips

Using Formatted Code

1. Copy to Editor:

  • Format your PHP code
  • Click "Copy Output"
  • Paste into your IDE
  • Test the code

2. Download File:

  • Format code
  • Click "Download .php"
  • Replace original file
  • Run and test

3. Combine with Composer:

# Format PHP code
# Then in terminal:
composer test
git add .
git commit -m "Format PHP code"

Setting Up Team Standards

1. Document style:

  • Indent: 4 spaces (PSR-12)
  • Follow PSR-12 standard
  • Use PHP-CS-Fixer for automation

2. Add to project:

  • Include in README
  • Add .editorconfig
  • Create .php-cs-fixer.php config
  • Set up pre-commit hooks

Note: For production PHP projects, we strongly recommend using PHP-CS-Fixer or PHP_CodeSniffer for full PSR-12 compliance and automated formatting. This tool is perfect for quick formatting, learning PHP style, and privacy-focused use cases.

Frequently Asked Questions

Most Viewed Tools

πŸ“Ί

Screen Size Converter

710 views

Calculate screen width and height from diagonal size and aspect ratio. Convert between inches and centimeters for displays, TVs, and monitors with instant dimension calculations.

Use Tool β†’
πŸ–¨οΈ

DPI Calculator

290 views

Calculate DPI (dots per inch), image dimensions, and print sizes. Convert between pixels and physical dimensions for printing and displays.

Use Tool β†’
πŸ“„

Paper Size Converter

251 views

Convert between international paper sizes (A4, Letter, Legal) with dimensions in mm, cm, and inches. Compare ISO A/B series and North American paper standards.

Use Tool β†’
β›½

Fuel Consumption Converter

237 views

Convert between MPG (miles per gallon), L/100km (liters per 100 kilometers), and other fuel efficiency units. Compare car fuel economy across different measurement systems.

Use Tool β†’
βœ‚οΈ

CSV Splitter

226 views

Split large CSV files into smaller files by number of rows. Process large datasets in manageable chunks instantly.

Use Tool β†’
πŸ›οΈ

Product Schema Generator

206 views

Generate JSON-LD Product schema markup for SEO. Add product details like name, price, brand, rating, and availability to create structured data for rich search results.

Use Tool β†’
πŸ“„

Large Text File Viewer

175 views

View and search large text files up to 200MB in your browser. Features virtual scrolling, line numbers, search functionality, and file statistics. Perfect for log files, CSV, JSON, and code files.

Use Tool β†’
πŸ”‘

API Key Generator

162 views

Generate secure, cryptographically random API keys for authentication and authorization. Create custom API keys with various formats including hex, base64, and prefixed keys.

Use Tool β†’

Related Utility Tools

Share Your Feedback

Help us improve this tool by sharing your experience

We will only use this to follow up on your feedback