PHP Syntax & Structure
In this page:
Semicolons
PHP uses a semicolon to mark the end of each statement, the same way a period ends a sentence — it's how the interpreter knows one instruction has finished and the next one is starting. Omitting it is one of the most common beginner errors, and it usually produces a 'parse error, unexpected token' pointing at the *next* line, not the missing one.
Example: Semicolons
<?php
echo "First statement";
echo "Second statement";
// Each statement ends with a semicolon, like a period ends a sentence
?>
Login to try C/C++/Java/PHP code in the editor
Case Sensitivity in PHP
Language keywords and built-in function names in PHP (if, echo, strlen) are case-insensitive, so ECHO and echo behave identically. Variable names are the opposite: $Name and $name are two completely different variables, so consistent casing matters a lot more for variables than for keywords.
Example: Case Sensitivity in PHP
<?php
ECHO "Keywords are case-insensitive.\n";
$Name = "Alice";
$name = "Bob";
echo "$Name and $name are different variables.";
?>
Login to try C/C++/Java/PHP code in the editor
Braces and Blocks
Curly braces { } mark where a block of code begins and ends — the body of a function, the branches of an if/else, or the body of a loop. Everything inside the braces executes together as a unit, which is what lets you group multiple statements under a single condition or loop.
Example: Braces and Blocks
<?php
if (true) {
echo "Statement one in the block.\n";
echo "Statement two in the block.\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Whitespace and Layout
PHP doesn't care about indentation or extra blank lines the way some languages do — they're purely for human readability. That said, consistent indentation makes nested blocks (loops inside conditions inside functions) far easier to read at a glance, so most style guides enforce it even though the interpreter doesn't require it.
Example: Whitespace and Layout
<?php
echo "Indentation is ignored by PHP";
echo "but blank lines don't matter either.";
?>
Login to try C/C++/Java/PHP code in the editor
Code Nesting
Because PHP tags can appear anywhere inside an HTML file, you can drop small PHP snippets directly into a template — printing a username in a <h1>, say — without converting the whole file to PHP. The server only executes what's between <?php and ?>; the surrounding HTML passes through untouched.
Example: Code Nesting
<?php $username = "Alice"; ?>
<h1>Welcome, <?php echo $username; ?></h1>
<p>This HTML passes through untouched.</p>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: