PHP code blocks
last modified May 17, 2025
PHP uses curly braces {} to define code blocks that organize program structure. These blocks create distinct scopes for variables and control flow. Proper block usage is essential for writing clean, maintainable PHP code.
Basic code blocks
PHP code blocks are created with curly braces under constructs like functions, conditionals, and loops. Blocks determine variable scope and code execution.
<?php declare (strict_types=1); // Function with a code block function calculateTotal($price, $quantity) { $subtotal = $price * $quantity; $tax = $subtotal * 0.08; return $subtotal + $tax; } echo "Total: " . number_format(calculateTotal(25.99, 3), 2) . "\n"; // Conditional with blocks function checkNumber($n) { if ($n > 0) { echo "Positive number\n"; echo "Double: " . ($n * 2) . "\n"; } else { echo "Non-positive number\n"; echo "Absolute: " . abs($n) . "\n"; } } checkNumber(5); checkNumber(-3);
This shows basic PHP code blocks in functions and conditionals. All statements within braces belong to the same block. Variables declared inside blocks have local scope.
λ php basic_blocks.php Total: 84.21 Positive number Double: 10 Non-positive number Absolute: 3
Nested blocks
Blocks can be nested by placing blocks inside other blocks. Each nested level creates a new scope while maintaining access to outer scopes.
<?php declare (strict_types=1); function analyzeNumbers($numbers) { if (empty($numbers)) { echo "No numbers to analyze\n"; } else { echo "Number count: " . count($numbers) . "\n"; $evens = array_filter($numbers, function($x) { return $x % 2 == 0; }); $odds = array_filter($numbers, function($x) { return $x % 2 != 0; }); echo "Even numbers: " . implode(', ', $evens) . "\n"; echo "Odd numbers: " . implode(', ', $odds) . "\n"; if (!empty($evens)) { echo "Even stats:\n"; echo " Min: " . min($evens) . "\n"; echo " Max: " . max($evens) . "\n"; } if (!empty($odds)) { echo "Odd stats:\n"; echo " Min: " . min($odds) . "\n"; echo " Max: " . max($odds) . "\n"; } } } analyzeNumbers(range(1, 10));
This example shows multiple levels of nested blocks. The outer function block contains conditional blocks, which themselves contain additional blocks. Each level is marked by its own set of braces.
λ php nested_blocks.php Number count: 10 Even numbers: 2, 4, 6, 8, 10 Odd numbers: 1, 3, 5, 7, 9 Even stats: Min: 2 Max: 10 Odd stats: Min: 1 Max: 9
Variable scope in blocks
PHP has function-level scope for variables. Variables declared in blocks are accessible throughout the function unless in a separate function or class method.
<?php declare (strict_types=1); function processUser($user) { $isValid = !empty($user['name']) && $user['age'] > 0; if ($isValid) { $greeting = $user['age'] >= 18 ? "Hello, " . $user['name'] : "Hi, " . $user['name'] . " (minor)"; echo $greeting . "\n"; $accountType = match(true) { $user['age'] >= 65 => "Senior", $user['age'] >= 18 => "Adult", default => "Junior" }; echo "Account type: $accountType\n"; } else { echo "Invalid user data\n"; } } processUser(['name' => 'Alice', 'age' => 30]); processUser(['name' => '', 'age' => 15]);
This demonstrates variable scope in PHP blocks. Variables declared in blocks are accessible throughout the function, but not outside it. The $greeting and $accountType variables are available after their blocks.
λ php variable_scope.php Hello, Alice Account type: Adult Invalid user data
Control structures
PHP control structures like loops and switches use blocks to organize their execution logic. These follow the same brace-based scoping rules.
<?php declare (strict_types=1); function printMultiples($n, $max) { $i = 1; while ($i <= $max) { if ($i % $n == 0) { echo "$i is a multiple of $n\n"; switch ($i) { case $n: echo " (first multiple)\n"; break; case $n * 2: echo " (second multiple)\n"; break; default: echo " (higher multiple)\n"; } } $i++; } } printMultiples(3, 10);
This shows blocks in while loops, if conditions, and switch statements. Each control structure uses braces to define its block scope, with variables accessible throughout the function.
λ php control_structures.php 3 is a multiple of 3 (first multiple) 6 is a multiple of 3 (second multiple) 9 is a multiple of 3 (higher multiple)
Class and method blocks
PHP classes and methods use blocks to define their structure. Class properties and methods are scoped within the class block.
<?php declare (strict_types=1); class Person { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function greet() { echo "Hello, my name is {$this->name}\n"; } public function isAdult() { return $this->age >= 18; } } $p = new Person('Alice', 30); $p->greet(); echo $p->isAdult() ? "Adult\n" : "Not adult\n";
This demonstrates class and method blocks in PHP. The class block contains property declarations and method definitions, each with their own blocks. The $this variable provides access to class members.
λ php class_blocks.php Hello, my name is Alice Adult
Anonymous functions
PHP supports anonymous functions (closures) that create their own scopes. These can capture variables from the parent scope with the use keyword.
<?php declare (strict_types=1); function createMultiplier($factor) { return function($n) use ($factor) { return $n * $factor; }; } $double = createMultiplier(2); $triple = createMultiplier(3); echo "Double of 5: " . $double(5) . "\n"; echo "Triple of 5: " . $triple(5) . "\n"; // Immediately-invoked function expression $result = (function($x, $y) { $sum = $x + $y; return $sum * 2; })(3, 4); echo "IIFE result: $result\n";
These examples show anonymous functions creating their own scopes. The use keyword captures variables from the parent scope. IIFEs execute immediately with their own block scope.
λ php anonymous_functions.php Double of 5: 10 Triple of 5: 15 IIFE result: 14
Best practices
Consistent brace style and indentation improve PHP code readability. Follow these practices for clean, maintainable code blocks.
<?php declare (strict_types=1); // Good practices example class Calculator { // Allman style braces public static function calculate($x, $y) { $intermediate = self::computeIntermediate($x, $y); if ($intermediate > 100) { echo "Large result\n"; return $intermediate / 10; } else { echo "Normal result\n"; return $intermediate; } } private static function computeIntermediate($a, $b) { return ($a * 2) + ($b * 3); } } // Keep blocks focused function processData($data) { $cleanData = array_filter($data, function($x) { return $x > 0; }); $processed = array_map(function($x) { return $x * 2; }, $cleanData); return [ 'sum' => array_sum($processed), 'avg' => array_sum($processed) / count($processed) ]; } // Avoid deep nesting // Use consistent indentation (4 spaces) // Keep block sizes reasonable
This example demonstrates good practices: consistent brace style, focused blocks, and clean organization. The class shows well-structured PHP code.
PHP code blocks provide clear structure through brace-delimited scopes. By understanding block scope and following consistent practices, you can write PHP code that's both organized and maintainable. Proper block usage makes control flow and variable scope immediately apparent.
Author
List all PHP tutorials.