PHP Syntax
PHP, a powerful server-side scripting language used in web development.
It’s simplicity and ease of use makes it an ideal choice for beginners and
experienced developers. This article provides an overview of PHP syntax.
PHP scripts can be written anywhere in the document within PHP tags along
with normal HTML.
Basic PHP Syntax
PHP code is executed between PHP tags, allowing the integration of PHP
code within HTML. The most common PHP tag is <?php ... ?>, which is used
to enclose PHP code. The <?php ....?> is called Escaping to PHP.
<?php
// code
?>
The script starts with <?php and ends with ?>. These tags are also called
'Canonical PHP tags'. Everything outside of a pair of opening and closing
tags is ignored by the PHP parser. The open and closing tags are called
delimiters. Every PHP command ends with a semi-colon (;).
Basic Example of PHP
<?php
// Here echo command is used to printecho "Hello, world!"; ?>
OutputHello, world!
PHP Variables
A variable in PHP is a container used to store data such as numbers, strings,
arrays, or objects. The value stored in a variable can be changed or updated
during the execution of the script.
• All variable names start with a dollar sign ($).
• Variables can store different data types, like integers, strings, arrays,
etc.
• PHP is loosely typed, so you don’t need to declare a data type
explicitly.
• Variable values can change during the script’s execution.
Declaring Variables in PHP
To declare a variable in PHP, you simply assign a value to it using the
$ symbol followed by the variable name. PHP variables are case-sensitive
and must start with a letter or an underscore, followed by any number of
letters, numbers, or underscores.
Syntax:
$variable_name = value;
Now, let us understand with the help of the example:
<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>
Variable Naming Conventions
In PHP, it’s important to follow certain naming conventions for PHP variables
to ensure readability and maintainability:
• Start with a Letter or Underscore: Variable names must begin with a
letter or an underscore (_), not a number.
• Use Descriptive Names: Variable names should be descriptive of their
purpose, e.g., $userName, $totalAmount.
• Case Sensitivity: PHP variable names are case-sensitive, meaning
$name and $Name are different variables.
• Avoid Reserved Words: Do not use PHP reserved words or keywords
as variable names (e.g., function, class, echo).
Example of Valid and Invalid Variable Names
<?php
$firstName = "Alice"; // Valid
$_age = 25; // Valid
$2ndPlace = "Bob"; // Invalid: Cannot start with a number
$class = "Physics"; // Valid, but avoid reserved words
?>
PHP Variable Scope
The scope of a variable refers to where it can be accessed within the code.
PHP variables can have local, global, static, or superglobal scope.
1. Local Scope or Local Variable
Variables declared within a function have local scope and cannot be
accessed outside the function. Any declaration of a variable outside the
function with the same name (as within the function) is a completely different
variable.
2. Global Scope or Global Variable
The variables declared outside a function are called global variables. These
variables can be accessed directly outside a function. To get access within a
function we need to use the “global” keyword before the variable to refer to
the global variable.
3. Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its
execution and the memory is freed. But sometimes we need to store the
variables even after the completion of function execution. To do this, we use
the static keywords and the variables are then called static variables. PHP
associates a data type depending on the value for the variable.
4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in
the script, including within functions. Common superglobals include $_GET,
$_POST, $_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.
PHP Data Types
Variables can store data of different types, and different data types can do different
things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16),
octal (base 8), or binary (base 2) notation
Example
$x = 5985;
var_dump($x);
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float. The var_dump() function returns the data type
and value:
Example
$x = 10.365;
var_dump($x);
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The var_dump() function returns the data
type and value:
Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
Let's assume we have a class named Car that can have properties like model, color,
etc. We can define variables like $model, $color, and so on, to hold the values of
these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for
the properties.
If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.
Example
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model .
"!";
}
}
$myCar = new Car("red", "Volvo");
var_dump($myCar);
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Variables can also be emptied by setting the value to NULL:
Example
$x = "Hello world!";
$x = null;
var_dump($x);
PHP Operators – Notes
1. Arithmetic Operators
Used to perform basic mathematical operations.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
Exponentiatio $x **
** $x raised to power $y
n $y
2. Assignment Operators
Used to assign values to variables.
Operator Example Same as
= $x = $y $x = $y
$x +=
+= $x = $x + $y
$y
$x -=
-= $x = $x - $y
$y
$x *=
*= $x = $x * $y
$y
$x /=
/= $x = $x / $y
$y
$x %=
%= $x = $x % $y
$y
3. Comparison Operators
Used to compare values.
Operator Name Example Result
$x ==
== Equal true if equal
$y
$x ===
=== Identical true if equal and same type
$y
$x !=
!= Not equal true if not equal
$y
$x <>
<> Not equal true if not equal
$y
$x !== true if not equal or not same
!== Not identical
$y type
> Greater than $x > $y true if $x is greater
< Less than $x < $y true if $x is smaller
Greater or $x >=
>= true if $x ≥ $y
equal $y
$x <=
<= Less or equal true if $x ≤ $y
$y
$x <=>
<=> Spaceship Returns -1, 0, or 1
$y
4. Increment / Decrement Operators
Used to increase or decrease a variable's value.
Operator Name Description
Increments $x, then returns
++$x Pre-increment
$x
Post-
$x++ Returns $x, then increments
increment
--$x Pre-decrement Decrements $x, then returns
Post-
$x-- Returns $x, then decrements
decrement
5. Logical Operators
Used to combine conditions.
Operator Name Example Result
$x and
and And true if both are true
$y
$x or
or Or true if either is true
$y
$x xor true if either but not
xor Xor
$y both
$x &&
&& And true if both are true
$y
` ` Or
! Not !$x true if $x is false
6. String Operators
Operator Name Example
$txt1 .
. Concatenation
$txt2
Concatenate $txt1 .=
.=
assignment $txt2
7. Array Operators
Used to compare or merge arrays.
Operator Name Description
+ Union Merges two arrays
== Equality Same key/value pairs
Same key/value pairs in same order &
=== Identity
type
!= Inequality Not equal
<> Inequality Not equal
!== Non-identity Not identical
8. Conditional Assignment Operators
Operator Name Example
$x = expr1 ? expr2 :
?: Ternary
expr3
Null
?? $x = expr1 ?? expr2
coalescing
PHP Constants
Overview
• Constants are identifiers for simple values that cannot be changed once defined.
• They start with a letter or underscore (no $ before the name).
• Unlike variables, constants are global across the entire script.
Defining Constants
• Using define()
define(name, value);
o name: constant name
o value: constant value
• Using const keyword
const CONSTANT_NAME = value;
o Cannot be used inside function or block scope (unlike define()).
Constant Arrays
define("CARS", ["Alfa Romeo", "BMW", "Toyota"]);
• From PHP 7 onward, you can define array constants using define().
Scope
• Constants are automatically global and can be used anywhere in the script,
including inside functions.
PHP switch Statement
• The switch statement is used to perform different actions based on different
conditions.
• It is often used instead of multiple if...else statements when checking the same
expression against different values.
• How it works:
o The switch expression is evaluated once.
o The value is compared to each case value.
o If a match is found, the corresponding code block runs.
o break; is used to stop further case checking (avoids fall-through).
o If no match is found, the default block is executed.
Syntax
cpp
CopyEdit
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
PHP Loops – Notes
Loops are used to execute a block of code repeatedly while a condition is true.
1. while Loop
• Repeats a block of code as long as the condition is true.
Syntax:
while (condition) {
// code
}
2. do...while Loop
• Executes the block once, then repeats as long as the condition is true.
Syntax:
do {
// code
} while (condition);
3. for Loop
• Used when the number of iterations is known.
Syntax:
for (init; condition; increment) {
// code
}
• init: set counter start value
• condition: test before each loop
• increment: change counter after each iteration
4. foreach Loop
• Loops through each item in an array.
Syntax:
foreach ($array as $value) {
// code
}
foreach ($array as $key => $value) {
// code
}
Loop Control Statements
• break; → Ends the loop immediately.
• continue; → Skips current iteration and moves to the next.
PHP Forms – Notes
What are Forms in PHP?
• HTML forms collect user input.
• PHP can process this input on the server side.
• Form data is sent to a PHP file specified in the action attribute.
Form Submission Methods
1. GET
a. Sends data appended to the URL as query strings.
b. Data is visible in the URL (less secure).
c. Length limitations (~2000 characters).
d. Can be bookmarked.
e. Suitable for non-sensitive data.
2. POST
a. Sends data in the HTTP request body (not shown in URL).
b. No size limits.
c. More secure than GET.
d. Cannot be bookmarked.
e. Preferred for sensitive data and file uploads.
HTML Form Example
<form action="welcome.php" method="post">
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
<input type="submit">
</form>
Collecting Form Data in PHP
• Use PHP superglobals:
o $_GET["fieldname"]
o $_POST["fieldname"]
$name = $_POST["name"];
$email = $_POST["email"];
PHP Arrays
An array stores multiple values in one single variable:
ExampleGet your own PHP Server
$cars = array("Volvo", "BMW", "Toyota");
What is an Array?
An array is a special variable that can hold many values under a single name, and you
can access the values by referring to an index number or name.
PHP Array Types
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Working With Arrays
In this tutorial you will learn how to work with arrays, including:
• Create Arrays
• Access Arrays
• Update Arrays
• Add Array Items
• Remove Array Items
• Sort Arrays
PHP Create Arrays
Create Array
You can create arrays by using the array() function:
ExampleGet your own PHP Server
$cars = array("Volvo", "BMW", "Toyota");
You can also use a shorter syntax by using the [] brackets:
Example
$cars = ["Volvo", "BMW", "Toyota"];
Multiple Lines
Line breaks are not important, so an array declaration can span multiple lines:
Example
$cars = [
"Volvo",
"BMW",
"Toyota"
];
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0 and
increased by 1 for each item, so the array above could also be created with keys:
Example
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
As you can see, indexed arrays are the same as associative arrays, but associative arrays
have names instead of numbers:
Example
$myCar = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
Declare Empty Array
You can declare an empty array first, and add items to it later:
Example
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The same goes for associative arrays, you can declare the array first, and then add items
to it:
Example
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
PHP Array Functions
1. count()
• Purpose: Returns the number of elements in an array.
Syntax:
count($array);
Example:
$arr = ["Apple", "Banana", "Cherry"];
echo count($arr); // 3
2. array_push()
• Purpose: Adds one or more elements to the end of an array.
Syntax:
array_push($array, val1, val2, ...);
Example:
$arr = ["Apple", "Banana"];
array_push($arr, "Cherry", "Mango");
3. array_pop()
• Purpose: Removes and returns the last element of an array.
Syntax:
array_pop($array);
Example:
$arr = ["Apple", "Banana", "Cherry"];
array_pop($arr); // removes Cherry
4. array_merge()
• Purpose: Combines two or more arrays into one.
Syntax:
array_merge($array1, $array2, ...);
Example:
$a1 = ["red", "green"];
$a2 = ["blue", "yellow"];
$result = array_merge($a1, $a2);
5. array_search()
• Purpose: Searches an array for a value and returns its key if found.
Syntax:
array_search(value, $array);
Example:
$arr = ["a" => "Apple", "b" => "Banana"];
$key = array_search("Banana", $arr); // b
6. sort()
• Purpose: Sorts an indexed array in ascending order (values only).
Syntax:
sort($array);
Example:
$arr = [3, 1, 2];
sort($arr); // [1, 2, 3]
7. array_reverse()
• Purpose: Returns an array with elements in reverse order.
Syntax:
array_reverse($array);
Example:
$arr = ["Apple", "Banana", "Cherry"];
$result = array_reverse($arr);
8. array_sum()
• Purpose: Returns the sum of array values.
Syntax:
array_sum($array);
Example:
$nums = [2, 4, 6];
echo array_sum($nums); // 12
9. array_unique()
• Purpose: Removes duplicate values from an array.
Syntax:
array_unique($array);
Example:
$arr = ["a" => "Apple", "b" => "Apple", "c" => "Banana"];
$result = array_unique($arr);
10. in_array()
• Purpose: Checks if a value exists in an array.
Syntax:
in_array(value, $array, strict);
Example:
$arr = ["Apple", "Banana"];
echo in_array("Banana", $arr);
PHP Functions
A function in PHP is a block of code designed to perform a specific
task. Functions help in reducing repetition, increasing reusability,
and making code easier to maintain.
Functions can be built-in (like strlen(), count()) or user-defined.
1. Defining a Function
• A user-defined function is created using the function keyword
followed by the function name and parentheses ().
• The function name should start with a letter or underscore, not a
number.
• The code inside {} will execute when the function is called.
Syntax:
function functionName() {
// code to be executed
}
Example:
function greet() {
echo "Hello, welcome to PHP!";
}
2. Calling a Function
• To execute the code inside a function, we call it by its name
followed by ().
• Functions can be called multiple times in the program.
Example:
greet(); // Output: Hello, welcome to PHP!
greet(); // Can be called again
3. Returning Values
• Functions can send data back to the calling code using the return
statement.
• The returned value can be stored in a variable for further use.
• A function can return any data type — number, string, array, etc.
Example:
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3); // $result holds 8
4. Variable Scope
Variables have different scopes depending on where they are declared:
1. Local Scope – Declared inside a function; can be used only inside
it.
function test() {
$x = 10; // local variable
echo $x;
}
2. Global Scope – Declared outside all functions; cannot be accessed
inside functions unless declared global.
$x = 5;
function test() {
global $x;
echo $x; // 5
}
3. Static Scope – Retains value between function calls.
function counter() {
static $count = 0;
$count++;
echo $count;
}
5. Function Arguments
• Arguments are values passed to a function to work with dynamic
input.
• Multiple arguments are separated by commas.
• Default Arguments – If no value is passed, the default value is
used.
• Pass by Value – Default method; original value not changed.
• Pass by Reference – Use & to allow the function to modify the
original variable.
Example:
function display($name = "Guest") {
echo "Hello, $name";
}
display("Priya");
display();
PHP Alternative Notes & Extra Tips
• PHP Syntax:
- Supports short echo tags <?= ?> (requires enabling in php.ini).
- Heredoc and Nowdoc allow clean multi-line string handling.
• Variables:
- Variable variables ($$var) allow dynamic variable naming.
- Use isset() and empty() before using a variable to avoid errors.
• Data Types:
- PHP 7+ supports scalar type declarations and return types.
- Type casting available: (int), (string), (array), etc.
• Operators:
- Null coalescing assignment (??=) introduced in PHP 7.4.
- Spaceship (<=>) useful for custom sorting functions.
<?php
$a = null;
$b = 'Hello';
$a ??= $b; // $a becomes 'Hello'
?>
<?php
usort($arr, fn($x, $y) => $x <=> $y);
?>
• Constants:
- Magic constants like __FILE__, __DIR__, __LINE__ give meta info.
• Loops:
- break n; allows breaking multiple nested loops.
- Generators (yield) provide memory-efficient iteration.
• Arrays:
- Use array_map(), array_filter(), array_reduce() for clean transformations.
- array_key_exists() is better than isset() for null values.
• Functions:
- Closures can capture variables with 'use'.
- Arrow functions (fn($x) => $x*2) are concise.
• Forms:
- Always sanitize input with htmlspecialchars() or filter_input().
- Validate file uploads for MIME type and size.
• General Tips:
- Use strict comparison (===) to prevent type juggling.
- Enable error display only in development environments.