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 ToolsHow to Use PHP Beautifier
Quick Start Guide
- Paste Code: Copy your messy PHP code into the input area
- Configure Options: Choose indent size, brace style, and spacing preferences
- Beautify: Click "Beautify Code" to format your PHP
- Copy or Download: Use the output buttons to copy or download the formatted code
- 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:
- Write your PHP code
- Format before committing
- Run PHP CodeSniffer for validation
- Run tests
- 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
Related Utility Tools
Temperature Converter
FeaturedConvert temperatures between Celsius, Fahrenheit, and Kelvin instantly with live conversion
Use Tool βUnit Converter
FeaturedConvert between length, weight, and volume units instantly. Support for metric and imperial systems.
Use Tool βWord Counter
FeaturedCount words, characters, sentences, and reading time instantly
Use Tool βArea Converter
FeaturedConvert areas between square feet, square meters, acres, hectares, and square yards instantly
Use Tool βTime Zone Converter
FeaturedConvert between time zones and see current or custom time across different parts of the world
Use Tool βSpeed Converter
FeaturedConvert speeds between miles per hour (MPH), kilometers per hour (KPH), and knots instantly
Use Tool βMinify JavaScript
Minify and compress JavaScript code to reduce file size for production. Remove comments, whitespace, and optimize code for faster loading.
Use Tool βPaper Size Converter
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 βShare Your Feedback
Help us improve this tool by sharing your experience