PHP Syntax
PHP syntax is the set of rules that tells the PHP interpreter how PHP code should be written and understood. Just as English has grammar rules, PHP has rules for statements, variables, operators, functions, strings, comments, conditions, loops, and other programming elements.
PHP is designed to be relatively easy to learn, especially for beginners who already know a little HTML. PHP code can be embedded directly into an HTML document, which makes it useful for creating dynamic websites and web applications.
Understanding PHP syntax is one of the most important first steps in learning PHP. Once the basic syntax becomes familiar, writing variables, processing forms, connecting to databases, creating functions, and building complete applications becomes much easier.
What Is PHP?
PHP is a server-side scripting language mainly used for web development. PHP code runs on a web server, and the server sends the resulting HTML or other response to the browser.
A simple PHP program looks like this:
<?php
echo "Hello, World!";
?>
The echo statement displays text.
The opening <?php tells the server that PHP code begins at that point.
The closing ?> indicates the end of a PHP block. However, the closing tag is optional when a file contains only PHP code, and omitting it is generally recommended.
For example:
<?php
echo "Hello, World!";
Both forms can work, but the second style is commonly preferred for PHP-only files.
PHP Tags
PHP code is normally placed between PHP tags.
The standard opening tag is:
<?php
For example:
<?php
$name = "Dibya";
echo $name;
?>
PHP can be mixed with HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My Website</h1>
<?php
echo "Welcome to my website!";
?>
</body>
</html>
This ability to combine PHP and HTML is one of the features that made PHP popular for web development.
The Standard PHP Opening Tag
The recommended and most widely used PHP opening tag is:
<?php
PHP begins interpreting code after this tag.
For example:
<?php
echo "PHP is running.";
The <?php tag should not be confused with short opening tags such as:
<?
Short tags have portability and configuration concerns and should generally be avoided in modern PHP code.
PHP Statements
A PHP program is commonly made up of statements. A statement tells PHP to perform an action.
Most PHP statements end with a semicolon (;).
Example:
<?php
echo "Hello";
echo "Welcome";
echo "PHP";
Each echo statement ends with ;.
The semicolon tells PHP where one statement ends.
Another example:
<?php
$name = "Rahul";
$age = 25;
echo $name;
echo $age;
Here, each assignment and output operation is a separate statement.
Semicolons in PHP
The semicolon is one of the most important syntax characters in PHP.
Correct:
<?php
$name = "Alex";
echo $name;
Incorrect:
<?php
$name = "Alex"
echo $name
The second example is missing semicolons and can produce a syntax error.
Although some PHP constructs have different structural rules, you should develop the habit of ending ordinary PHP statements with semicolons.
PHP Is Case-Sensitive in Important Places
PHP has different case-sensitivity rules depending on what is being written.
Variable names are case-sensitive.
For example:
$name = "John";
echo $name;
This is different from:
echo $Name;
$name and $Name are different variables.
Similarly:
$age = 20;
$Age = 30;
echo $age;
echo $Age;
The two variables contain different values.
PHP keywords, language constructs, and many built-in constructs are generally not case-sensitive, but modern PHP coding standards strongly favor lowercase keywords.
For example:
if ($age >= 18) {
echo "Adult";
}
is the normal style.
PHP Variables
Variables are used to store information.
A PHP variable begins with the dollar sign ($).
Example:
<?php
$name = "John";
$age = 25;
$price = 99.50;
The variable name comes after $.
General form:
$variableName = value;
For example:
$city = "Bhubaneswar";
The variable $city stores the string "Bhubaneswar".
Rules for PHP Variable Names
PHP variable names follow several important rules.
A variable must begin with $ followed by a valid identifier.
Valid examples include:
$name
$age
$userName
$total_price
A variable name can contain letters, numbers, and underscores, but it cannot begin with a number.
Valid:
$user1
Invalid:
$1user
Variable names are also case-sensitive:
$name
$Name
$NAME
These represent different variables.
A descriptive variable name is usually better than a vague one:
$customerName = "Ravi";
is easier to understand than:
$x = "Ravi";
Assigning Values
The assignment operator is =.
Example:
$name = "Priya";
This means the value "Priya" is assigned to $name.
Numbers can also be assigned:
$age = 30;
Boolean values can be assigned:
$isLoggedIn = true;
Arrays can be assigned:
$colors = ["red", "green", "blue"];
Output with echo
echo is commonly used to output information.
Example:
<?php
echo "Hello, World!";
You can output a variable:
$name = "John";
echo $name;
You can also output multiple expressions:
$name = "John";
$age = 25;
echo $name, $age;
For readable output, you can use HTML:
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
The print Statement
PHP also provides print.
Example:
print "Hello, World!";
You can also print a variable:
$name = "John";
print $name;
Both echo and print are used for output, but echo is more commonly used when simply displaying content.
Strings
A string is a sequence of characters.
PHP supports both single-quoted and double-quoted strings.
Single quotes:
$name = 'John';
Double quotes:
$name = "John";
Double-quoted strings can interpret variables:
$name = "John";
echo "Hello, $name";
Output:
Hello, John
With single quotes:
echo 'Hello, $name';
the variable is generally treated as ordinary text.
String Concatenation
PHP uses the dot (.) operator to join strings.
Example:
$firstName = "John";
$lastName = "Smith";
$fullName = $firstName . " " . $lastName;
echo $fullName;
Output:
John Smith
The dot is called the concatenation operator.
Comments in PHP
Comments are notes written for programmers. PHP does not execute them.
PHP supports single-line and multi-line comments.
Single-line comment:
// This is a comment
Another single-line style:
# This is also a comment
Multi-line comment:
/*
This is a
multi-line comment.
*/
Example:
<?php
// Store the user's name
$name = "John";
echo $name;
Comments make code easier to understand and maintain.
PHP Whitespace
PHP generally ignores unnecessary spaces, tabs, and line breaks outside places where they affect the meaning of the code.
For example:
$name = "John";
and:
$name = "John";
work in the same basic way.
However, good formatting is important for humans. Clean formatting makes code easier to read and maintain.
Preferred:
if ($age >= 18) {
echo "Adult";
}
Rather than putting everything on one line.
PHP Code Blocks
Many PHP structures use curly braces ({}) to define a block of code.
For example:
if ($age >= 18) {
echo "You are an adult.";
}
The opening brace starts the block, while the closing brace ends it.
Blocks are commonly used with:
ifelseelseif- loops
- functions
- classes
- methods
- exception handling
PHP if Statement
The if statement executes code when a condition is true.
Example:
$age = 20;
if ($age >= 18) {
echo "Adult";
}
The general syntax is:
if (condition) {
// code
}
PHP else Statement
else provides an alternative when the if condition is false.
$age = 16;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
PHP elseif Statement
elseif allows multiple conditions to be checked.
$marks = 75;
if ($marks >= 90) {
echo "Excellent";
} elseif ($marks >= 60) {
echo "Good";
} else {
echo "Needs improvement";
}
Comparison Operators
PHP uses comparison operators to compare values.
Common comparison operators include:
| Operator | Meaning |
|---|---|
== | Equal in value |
=== | Identical in value and type |
!= | Not equal |
!== | Not identical |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example:
$age = 20;
if ($age >= 18) {
echo "Eligible";
}
Strict comparisons are especially useful when type matters:
if ($value === 10) {
echo "The value is exactly integer 10.";
}
Logical Operators
Logical operators combine conditions.
Common operators include:
&& AND
|| OR
! NOT
Example:
$age = 25;
$hasId = true;
if ($age >= 18 && $hasId) {
echo "Access allowed.";
}
PHP Functions
A function is a reusable block of code.
Example:
function greet() {
echo "Hello!";
}
The function can then be called:
greet();
A function can accept parameters:
function greet($name) {
echo "Hello, " . $name;
}
greet("John");
A function can also return a value:
function add($a, $b) {
return $a + $b;
}
$result = add(10, 20);
echo $result;
Modern PHP also supports parameter and return type declarations:
function add(int $a, int $b): int {
return $a + $b;
}
Type declarations can make code clearer and help detect incorrect values.
PHP Arrays
Arrays store multiple values.
An indexed array can be written as:
$colors = ["red", "green", "blue"];
Values can be accessed using indexes:
echo $colors[0];
Output:
red
Associative arrays use named keys:
$person = [
"name" => "John",
"age" => 25
];
echo $person["name"];
PHP Loops
Loops repeat code.
A for loop:
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
A while loop:
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
A foreach loop is commonly used with arrays:
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color;
}
PHP Object-Oriented Syntax
PHP supports object-oriented programming.
A simple class looks like this:
class Person {
public string $name;
public function greet(): void {
echo "Hello!";
}
}
An object can be created using new:
$person = new Person();
$person->name = "John";
$person->greet();
The -> operator is used to access an object’s properties and methods.
PHP Constants
Constants store values that should not change during normal program execution.
A constant can be declared using const:
const SITE_NAME = "My Website";
It can then be used without $:
echo SITE_NAME;
PHP also provides define():
define("APP_NAME", "My Application");
echo APP_NAME;
By convention, constant names are commonly written in uppercase.
PHP Namespaces
Namespaces help organize code and prevent naming conflicts.
Example:
namespace App\Models;
class User {
}
Another namespace can contain a class with the same short name:
namespace App\Admin;
class User {
}
The fully qualified names are different, so the classes can coexist.
The use Statement
The use statement can import a class, function, or constant into the current namespace.
Example:
use App\Models\User;
You can then refer to User instead of its full namespace path.
PHP Include and Require
PHP allows one file to load another.
Using include:
include "header.php";
Using require:
require "config.php";
These are useful for sharing common code such as headers, configuration files, functions, and templates.
There are also:
include_once "header.php";
require_once "config.php";
The _once forms prevent the same file from being included more than once during a request.
PHP Alternative Syntax
PHP provides alternative syntax for some control structures, which can be useful when PHP is mixed heavily with HTML.
For example:
<?php if ($loggedIn): ?>
<p>Welcome!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>
This can make HTML-heavy templates easier to read.
PHP Short Echo Tag
PHP provides the short echo tag:
<?= $name ?>
It is commonly used in templates to output a value.
For example:
<h2><?= $title ?></h2>
The short echo syntax is intended specifically for output and is different from the short <? opening tag.
PHP Escape Characters
Escape sequences allow special characters to be represented inside strings.
For example:
echo "He said \"Hello\"";
The backslash escapes the double quote.
A newline can be represented with:
echo "Hello\nWorld";
For HTML output, remember that HTML escaping is a separate concern. When displaying untrusted user data in HTML, functions such as htmlspecialchars() are commonly used.
Example:
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
PHP Operators
PHP supports many types of operators.
Arithmetic:
+ - * / % **
Assignment:
= += -= *= /= .=
Comparison:
== === != !== > < >= <=
Logical:
&& || !
String:
.
Increment and decrement:
++
--
Example:
$a = 10;
$b = 5;
$result = $a + $b;
echo $result;
PHP Increment and Decrement
The increment operator increases a value by one.
$count = 1;
$count++;
The decrement operator decreases a value by one.
$count = 5;
$count--;
These operators are frequently used in loops.
PHP Type Declarations
Modern PHP supports type declarations for parameters, properties, and return values.
Example:
function multiply(int $a, int $b): int {
return $a * $b;
}
A nullable type can be written using ?:
function findName(?int $id): ?string {
return null;
}
PHP also supports union types:
function formatValue(int|string $value): string {
return (string) $value;
}
Type declarations improve clarity and can help catch programming mistakes.
PHP Strict Typing
PHP supports strict scalar type checking with:
declare(strict_types=1);
It is commonly placed at the beginning of a PHP file:
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
When strict typing is enabled, PHP applies stricter rules when passing scalar values to typed parameters.
PHP Error and Exception Syntax
PHP provides exceptions for handling exceptional situations.
Example:
try {
throw new Exception("Something went wrong.");
} catch (Exception $e) {
echo $e->getMessage();
}
A finally block can be used when code should run regardless of whether an exception occurred:
try {
// Code that may fail
} catch (Exception $e) {
// Handle exception
} finally {
// Cleanup
}
Modern PHP applications often use specific exception classes rather than catching every exception with a broad Exception handler.
PHP Match Expression
Modern PHP versions include the match expression.
Example:
$status = 200;
$message = match ($status) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown Status"
};
echo $message;
Unlike the traditional switch statement, match uses strict comparison and returns a value.
PHP Switch Statement
The traditional switch statement is useful when comparing one expression against several possible values.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "End of the work week";
break;
default:
echo "Another day";
}
The break statement prevents execution from continuing into the next case.
PHP Ternary Operator
The ternary operator provides a compact way to choose between two values.
$age = 20;
$message = $age >= 18 ? "Adult" : "Minor";
echo $message;
General syntax:
condition ? valueIfTrue : valueIfFalse
For simple conditions, this can make code shorter. However, complicated nested ternary expressions can reduce readability.
Null Coalescing Operator
The null coalescing operator is ??.
It provides a fallback when a value is not set or is null.
Example:
$name = $_GET["name"] ?? "Guest";
echo $name;
This is often useful when reading optional input.
PHP also supports the null coalescing assignment operator:
$name ??= "Guest";
PHP Object Access Operators
The -> operator accesses members of an object:
$user->name;
The :: operator is used for static members and class constants:
User::find();
For example:
class MathHelper {
public const PI = 3.14159;
}
echo MathHelper::PI;
PHP Scope Resolution
The scope resolution operator :: is also used to access static properties, static methods, and class constants.
Example:
class Counter {
public static int $count = 0;
}
Counter::$count++;
It is also used with self, parent, and static in class code.
self::$count;
parent::method();
static::method();
PHP Heredoc Syntax
Heredoc syntax is useful for creating multi-line strings.
Example:
$message = <<<TEXT
Hello,
Welcome to PHP.
Have a great day!
TEXT;
echo $message;
The closing identifier must follow PHP’s heredoc syntax rules.
Heredoc strings behave similarly to double-quoted strings regarding variable interpolation.
PHP Nowdoc Syntax
Nowdoc is useful when you want a multi-line string without variable interpolation.
Example:
$message = <<<'TEXT'
Hello, $name
This text is treated literally.
TEXT;
echo $message;
Nowdoc syntax is similar to single-quoted strings but supports multiple lines.
PHP Closing Tags
A PHP file containing only PHP code does not need a closing tag.
Preferred:
<?php
$name = "John";
echo $name;
Instead of:
<?php
$name = "John";
echo $name;
?>
Omitting the closing tag can help prevent accidental whitespace or output after the PHP code.
For PHP files that contain HTML after the PHP section, the closing tag may be appropriate:
<?php
$name = "John";
?>
<h1>Hello, <?= $name ?></h1>
Embedding PHP in HTML
PHP is often embedded in HTML.
Example:
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1>Welcome</h1>
<?php
$name = "John";
echo "<p>Hello, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "</p>";
?>
</body>
</html>
PHP generates or modifies the content that the web server sends to the browser.
PHP Syntax and HTML Are Different
PHP and HTML have different roles.
HTML describes the structure of a web page.
PHP performs server-side processing.
For example:
<h1>Welcome</h1>
<?php
echo "<p>This paragraph was generated by PHP.</p>";
?>
The browser ultimately receives HTML. It does not normally receive the PHP source code.
PHP Syntax Errors
A syntax error occurs when PHP code does not follow the language’s grammar.
For example:
<?php
$name = "John"
echo $name;
The missing semicolon can cause a parse error.
Another example:
if ($age >= 18 {
echo "Adult";
}
The closing parenthesis is missing.
Syntax errors should be corrected before the program can execute successfully.
Common PHP Syntax Mistakes
Beginners often make a few common mistakes.
Forgetting the Dollar Sign
Incorrect:
name = "John";
Correct:
$name = "John";
Forgetting the Semicolon
Incorrect:
$name = "John"
Correct:
$name = "John";
Using the Wrong Comparison Operator
Be careful when distinguishing assignment from comparison.
$age = 18;
assigns a value.
$age == 18
performs a loose comparison.
$age === 18
performs a strict comparison.
Incorrect Variable Capitalization
$name = "John";
echo $Name;
$Name is not the same variable as $name.
Missing Braces
Incorrect:
if ($age >= 18)
echo "Adult";
This can be valid for a single statement, but braces are often preferable for clarity and safer future modifications.
Preferred:
if ($age >= 18) {
echo "Adult";
}
Unclosed Quotes
Incorrect:
echo "Hello;
Correct:
echo "Hello";
Unclosed Parentheses
Incorrect:
echo strtoupper("hello";
Correct:
echo strtoupper("hello");
PHP Syntax Best Practices
Writing syntactically correct code is only the beginning. Good PHP code should also be easy to read and maintain.
Use meaningful variable names:
$customerEmail = "user@example.com";
rather than:
$x = "user@example.com";
Use consistent indentation:
if ($isActive) {
echo "Active";
}
Keep functions focused on one clear task.
Use strict comparisons where appropriate:
if ($status === "active") {
// ...
}
Use type declarations when they make the intended data types clearer.
Avoid unnecessary complexity.
Write comments for decisions or non-obvious behavior rather than commenting every obvious line.
Follow a consistent coding standard, such as PSR-12, when working on professional PHP projects.
A Complete Simple PHP Example
The following example combines several basic syntax features:
<?php
declare(strict_types=1);
$name = "Dibya";
$age = 25;
function getGreeting(string $name): string
{
return "Hello, " . $name . "!";
}
echo getGreeting($name);
if ($age >= 18) {
echo "<p>You are an adult.</p>";
} else {
echo "<p>You are a minor.</p>";
}
This example demonstrates:
- PHP opening syntax
- strict typing
- variables
- strings
- functions
- parameters
- return types
- concatenation
- function calls
- conditional statements
- comparison operators
- semicolons
- curly braces
PHP Syntax Cheat Sheet
| Feature | Basic Syntax |
|---|---|
| PHP opening tag | <?php |
| Variable | $name |
| Assignment | $name = "John"; |
| Output | echo "Hello"; |
| Comment | // Comment |
| Multi-line comment | /* Comment */ |
| Condition | if ($x > 5) { } |
| Alternative condition | else { } |
| Function | function test() { } |
| Array | $items = [1, 2, 3]; |
| Object creation | $obj = new ClassName(); |
| Object member | $obj->name |
| Static member | ClassName::$value |
| Class constant | ClassName::VALUE |
| Concatenation | $a . $b |
| Strict comparison | $a === $b |
| Logical AND | $a && $b |
| Logical OR | $a || $b |
| Null coalescing | $a ?? $b |
| Ternary | $a ? $b : $c |
Why Learning PHP Syntax Matters
PHP syntax is the foundation for everything you do with the language. A developer who understands the syntax can read existing PHP projects more easily, identify errors faster, and write cleaner applications.
You do not need to memorize every PHP feature at once. Start with the fundamentals:
- PHP tags
- Statements and semicolons
- Variables
- Strings and numbers
- Operators
- Conditions
- Loops
- Functions
- Arrays
- Classes and objects
- Exceptions
- Namespaces
- Type declarations
After these concepts become familiar, advanced PHP features become much easier to understand.
Final Thoughts
PHP syntax provides the basic structure needed to communicate instructions to the PHP interpreter. Its core rules are straightforward: use <?php to begin PHP code, use $ for variables, end ordinary statements with semicolons, use braces for code blocks, and follow the correct rules for functions, conditions, loops, arrays, classes, and other language features.
Good PHP programming is not only about making code work. It is also about making code readable, predictable, secure, and maintainable. Meaningful names, consistent formatting, appropriate type declarations, strict comparisons, useful comments, and modern coding practices can make a significant difference.
Once you understand the fundamentals of PHP syntax, you have a strong foundation for learning database programming, form handling, APIs, object-oriented programming, frameworks, authentication, and full-stack web development.