PHP Syntax, Variables, and Data Types

Part of the course: php professional

PHP Syntax, Variables, and Data Types

1. Introduction to PHP Syntax

PHP (Hypertext Preprocessor) is a powerful, open-source scripting language designed primarily for web development. It is embedded within HTML and executed on the server side, which means the code is processed on the server, and the resulting HTML is sent to the client’s browser. Understanding PHP’s syntax is the first step in writing effective and error-free programs.

1.1 What Is PHP?

PHP is a server-side scripting language used to build dynamic web pages and applications. It can interact with databases, handle forms, manage sessions, and generate dynamic content. PHP scripts are usually saved with the .php extension and executed by a web server such as Apache or Nginx.
Example:

<?php
echo "Hello, World!";
?>

When this code runs on a server, it displays Hello, World! in the browser.


1.2 Embedding PHP in HTML

One of PHP’s strengths is its ability to be easily embedded within HTML. You can mix PHP code and HTML markup in the same file. This allows developers to create dynamic pages that include both static content (HTML) and dynamic content (PHP output).
Example:

<!DOCTYPE html>
<html>
<body>
<h1>Welcome!</h1>
<p>Today’s date is:
<?php echo date("Y-m-d"); ?>
</p>
</body>
</html>

Here, the HTML structure remains static, while PHP dynamically generates the date.


1.3 PHP Tags and Structure

All PHP code must be written inside PHP tags, which tell the server where PHP code begins and ends.
Common tag styles:

<?php ... ?> // Standard and recommended
<?= ... ?> // Short echo tag (outputs content)

Anything outside these tags is treated as plain HTML. PHP scripts are executed from top to bottom, just like other programming languages.


1.4 PHP Statements and Semicolons

Each PHP statement must end with a semicolon (;). This tells the PHP interpreter where one instruction ends and another begins.
Example:

<?php
$greeting = "Hello";
$name = "Alice";
echo $greeting . ", " . $name . "!";
?>

If you forget the semicolon, PHP will generate a syntax error.


1.5 Whitespace and Indentation

Whitespace (spaces, tabs, new lines) in PHP is ignored by the interpreter, but it’s crucial for readability. Developers use indentation and spacing to structure their code clearly.
Example (well formatted):

<?php
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>

Consistent indentation makes code easier to read and maintain.


1.6 Comments in PHP

Comments are used to explain code and are ignored during execution. PHP supports single-line and multi-line comments:
Examples:

<?php
// This is a single-line comment
# This is also a single-line comment/*
This is a multi-line comment.
It can span several lines.
*/

?>

Using comments helps make code more understandable to others and to your future self.

2. Basic PHP Syntax Elements

Understanding PHP’s basic syntax elements is essential for writing clean, functional, and error-free code. This section explains how PHP treats different elements such as case sensitivity, keywords, identifiers, output statements, and the general flow of execution in a PHP program.


2.1 Case Sensitivity

In PHP, variable names are case-sensitive, but function names and keywords are not.
This means $name, $Name, and $NAME are considered three different variables, while functions such as echo, ECHO, and EcHo all behave the same.

Example:

<?php
$name = "Alice";
echo $name; // Works fine
echo $Name; // Error: Undefined variable
?>

Here, $Name is undefined because PHP treats it as a different variable from $name.

However, in the case of functions:

<?php
ECHO "Hello, World!"; // Works the same as echo
?>

All variations of letter casing for echo are valid.

Tip: For consistency and readability, it’s best to use lowercase for keywords and function names and follow a consistent variable naming convention.


2.2 Keywords and Identifiers

Keywords are reserved words that have special meaning in PHP’s syntax. You cannot use them as variable names, function names, or constants. Examples include:
if, else, while, function, return, echo, class, for, foreach, new, try, and catch.

Identifiers are the names you assign to variables, functions, classes, and constants. They must follow certain rules:

  • Must begin with a letter or underscore (_).

  • Cannot start with a number.

  • Can only contain letters, numbers, and underscores.

  • Are case-sensitive.

Examples of valid identifiers:

$userName
$_count
$total_amount

Invalid identifiers:

2ndUser // Starts with a number
user-name // Contains a hyphen
class // Reserved keyword

Tip: Use meaningful identifiers that describe the data or purpose, such as $userEmail or $totalPrice.


2.3 Outputting Data with echo and print

PHP provides two main ways to output data to the browser: echo and print. Both are used to display text, variables, or HTML.

Using echo

  • Can output one or more strings separated by commas.

  • Slightly faster than print.

  • Does not return a value.

Example:

<?php
echo "Hello, World!";
echo "<br>", "This is PHP!";
?>

Using print

  • Can output only one string at a time.

  • Returns the value 1, so it can be used in expressions.

Example:

<?php
print "Welcome to PHP!";
if (print "Hello!") {
// This condition is true because print returns 1
}
?>

Both are commonly used, but echo is preferred for general use because it’s simpler and faster.


2.4 PHP Code Execution Flow

PHP scripts are executed sequentially from top to bottom — line by line.
The server processes each PHP statement inside <?php ... ?> tags in order, executes the code, and then outputs the result as plain HTML to the client’s browser.

Example:

<?php
echo "Step 1<br>";
echo "Step 2<br>";
echo "Step 3<br>";
?>

Output:

Step 1
Step 2
Step 3

If an error occurs during execution (for example, a missing semicolon), PHP will stop running the script at that point and display an error message, depending on the error reporting settings.

3. Variables in PHP

Variables are one of the most important building blocks of PHP programming. They act as containers for storing data such as numbers, strings, arrays, or objects. PHP variables are dynamic — you don’t need to declare their data type explicitly because PHP automatically determines it based on the value assigned.


3.1 Declaring Variables

In PHP, variables are declared using the dollar sign ($) followed by the variable name.
A variable does not need to be declared before assigning a value — simply assign a value to create it.

Example:

<?php
$name = "Alice";
$age = 25;
$price = 10.99;
?>

Here:

  • $name holds a string value ("Alice"),

  • $age holds an integer,

  • $price holds a floating-point number.

PHP automatically recognizes the type of data stored in the variable.

Tip: Always initialize variables before using them to avoid warnings or unexpected results.


3.2 PHP Variable Naming Rules

When naming variables in PHP, you must follow specific rules:

  1. Variable names must start with a dollar sign ($).

  2. The first character after $ must be a letter or underscore (_).

  3. Variable names can contain letters, numbers, and underscores only (no spaces or special characters).

  4. Variable names are case-sensitive ($Name and $name are different variables).

Examples of valid variable names:

$userName
$_total
$count1

Invalid variable names:

$1stUser // Starts with a number
$user-name // Contains a hyphen
$full name // Contains a space

Best Practice: Use descriptive names that clearly represent the data (e.g., $userEmail instead of $u).


3.3 Assigning Values to Variables

You can assign a value to a variable using the assignment operator (=).
PHP allows you to assign different data types easily.

Example:

<?php
$message = "Hello, PHP!";
$number = 42;
$price = 19.99;
$isAdmin = true;
?>

You can also assign one variable to another:

<?php
$a = 10;
$b = $a; // $b now holds 10
?>

PHP supports variable re-assignment — the same variable can hold different data types at different times (because PHP is loosely typed).


3.4 Variable Scope

A variable’s scope determines where it can be accessed within a script. PHP has four main types of variable scope:

Local Variables

Declared inside a function and accessible only within that function.

<?php
function test() {
$x = 5; // Local variable
echo $x;
}
test();
// echo $x; // Error: $x is not accessible here
?>

Global Variables

Declared outside of all functions and accessible throughout the script, except inside functions (unless declared as global).

<?php
$x = 10;
function showValue() {
global $x;
echo $x; // Accessing global variable inside a function
}
showValue();
?>

Static Variables

A static variable retains its value even after the function ends.
It is initialized only once.

<?php
function counter() {
static $count = 0;
$count++;
echo $count;
}
counter(); // 1
counter(); // 2
counter(); // 3
?>

Superglobals

Superglobals are built-in global variables accessible anywhere, without needing global.
Examples include:

  • $_GET – Collects data sent via URL parameters.

  • $_POST – Collects form data sent via POST.

  • $_SERVER – Provides server and execution environment information.

  • $_SESSION and $_COOKIE – Manage session and cookie data.

  • $_FILES – Handles file uploads.

  • $_REQUEST – Contains data from GET, POST, and COOKIE.

Example:

<?php
echo $_SERVER['SERVER_NAME'];
?>

3.5 Variable Variables ($$var)

PHP allows you to create variable variables, where the value of one variable determines the name of another.

Example:

<?php
$varName = "color";
$$varName = "blue";

echo $color; // Outputs: blue
?>

Explanation:

  • $varName contains the string "color".

  • $$varName becomes $color, and its value is set to "blue".

Use this feature carefully — while powerful, it can make code hard to read and debug.


3.6 Constants in PHP (define() and const)

Constants are fixed values that cannot be changed once defined. They are useful for storing values such as configuration settings or database credentials.

You can define constants in two ways:

Using define()

<?php
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite
?>

Using const (from PHP 5.3+)

<?php
const PI = 3.14159;
echo PI;
?>

Differences:

  • define() works only at runtime, while const is defined at compile time.

  • Constants are global and can be accessed anywhere in the script.

  • Constant names are case-sensitive by default (you can make them case-insensitive using a third argument in define()).

 

4. Data Types in PHP

Every variable in PHP stores data of a certain type, which determines what kind of values it can hold and what operations can be performed on it.
PHP is a loosely typed language — this means you don’t have to declare a variable’s type explicitly. PHP automatically converts data types as needed during execution.

Understanding PHP data types is crucial for writing reliable, predictable, and efficient programs.


4.1 Overview of PHP Data Types

PHP supports eight main data types, divided into three categories:

  1. Scalar types – represent a single value (e.g., integer, float, string, boolean)

  2. Compound types – can contain multiple values (e.g., array, object)

  3. Special types – used for special cases (e.g., NULL, resource)

Each data type behaves differently when used in operations or compared with others.


4.2 Scalar Data Types

Scalar data types hold one simple value at a time. Let’s go through each:

String

A string is a sequence of characters enclosed in quotes. You can use either single quotes (') or double quotes (").

Example:

<?php
$name = "Alice";
echo 'Hello, ' . $name; // Concatenation
echo "Hello, $name"; // Variable interpolation
?>

Difference between single and double quotes:

  • Single quotes display text as-is.

  • Double quotes parse variables and escape sequences (like \n for a new line).


Integer

An integer is a whole number (positive, negative, or zero) without a decimal point.

Example:

<?php
$age = 25;
$year = -2025;
echo $age + 5; // Outputs: 30
?>

PHP automatically treats numeric values without decimals as integers.


Float (Double)

A float (also called a double) is a number with a decimal point or in exponential form.

Example:

<?php
$price = 19.99;
$tax = 0.08;
$total = $price + ($price * $tax);
echo $total;
?>

Floating-point numbers are used in calculations involving fractions or real-world measurements (like prices, percentages, etc.).


Boolean

A boolean represents only two values: TRUE or FALSE.

Example:

<?php
$isLoggedIn = true;
if ($isLoggedIn) {
echo "Welcome back!";
} else {
echo "Please log in.";
}
?>

Booleans are commonly used in conditional statements to control program flow.


4.3 Compound Data Types

Compound types can store multiple values or complex data structures.

Array

An array is a collection of values stored under a single variable name.
Each value is associated with an index (numeric or associative).

Example (Indexed Array):

<?php
$colors = ["red", "green", "blue"];
echo $colors[1]; // Outputs: green
?>

Example (Associative Array):

<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "London"
];
echo $person["city"]; // Outputs: London
?>

Arrays can hold any data type — even other arrays or objects — making them very flexible.


Object

An object is an instance of a class. Objects are used in object-oriented programming (OOP) to group data (properties) and behavior (methods) together.

Example:

<?php
class Car {
public $brand;
public $color;

function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}

function display() {
echo “This car is a $this->color $this->brand.”;
}
}

$myCar = new Car(“Toyota”, “Red”);
$myCar->display(); // Outputs: This car is a Red Toyota.
?>

Objects make PHP powerful for building complex applications.


4.4 Special Data Types

NULL

The NULL data type represents a variable with no value.
A variable becomes NULL if it has been assigned the value NULL, has not been set, or has been unset.

Example:

<?php
$var = null;
if (is_null($var)) {
echo "The variable is null.";
}
?>

Resource

A resource is a special variable that holds a reference to an external resource — for example, a file handle, database connection, or cURL session.

Example:

<?php
$file = fopen("example.txt", "r"); // $file is a resource
echo get_resource_type($file); // Outputs: stream
fclose($file);
?>

Resources are managed by PHP internally and should always be closed or freed when no longer needed.


4.5 Type Juggling and Type Casting

PHP automatically converts data types when necessary — this behavior is called type juggling.
For example, when adding a string containing a number to an integer, PHP converts the string to a number.

Example:

<?php
$x = "10";
$y = 5;
$z = $x + $y; // "10" is converted to 10
echo $z; // Outputs: 15
?>

You can also manually convert a variable’s type using type casting:

<?php
$num = "25";
$num = (int)$num; // Casts to integer
var_dump($num); // int(25)
?>

Available casts: (int), (float), (string), (bool), (array), (object), (unset).


4.6 Checking Data Types with var_dump() and gettype()

PHP provides several functions to inspect variables and check their data types.

var_dump()

Displays both the type and value of a variable — very useful for debugging.

<?php
$test = 42;
var_dump($test);
// Output: int(42)
?>

gettype()

Returns only the type of the variable as a string.

<?php
$price = 19.99;
echo gettype($price); // Outputs: double
?>

Other useful functions include:

  • is_int(), is_string(), is_array(), is_null(), etc. — to check specific types.

 

 

 

 

5. Working with Variables and Data Types

Now that you understand PHP variables and data types, it’s time to explore how to work with them in real-world scenarios. This section covers common operations such as manipulating strings, performing mathematical calculations, comparing values, working with arrays, and converting between data types.


5.1 String Operations and Concatenation

Strings are one of the most commonly used data types in PHP. You can manipulate them using concatenation, interpolation, and string functions.

Concatenation (Combining Strings)

You can join two or more strings using the concatenation operator (.).

Example:

<?php
$firstName = "Alice";
$lastName = "Johnson";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: Alice Johnson
?>

The . operator connects strings together. You can also append a string using .=:

<?php
$message = "Hello";
$message .= " World!";
echo $message; // Outputs: Hello World!
?>

String Interpolation

If you use double quotes, PHP can insert variable values directly into strings.

<?php
$name = "Alice";
echo "Hello, $name!"; // Outputs: Hello, Alice!
?>

Note: Single quotes ' ' will not interpret variables inside the string.

Useful String Functions

PHP provides many built-in string functions:

strlen("Hello") // Returns 5
strtoupper("php") // Returns "PHP"
strtolower("HELLO") // Returns "hello"
str_replace("world", "PHP", "Hello world") // Returns "Hello PHP"
substr("Hello PHP", 0, 5) // Returns "Hello"

Tip: Strings are very flexible in PHP — use the right functions for text processing, formatting, or validation.


5.2 Arithmetic and Assignment Operators

PHP allows you to perform mathematical calculations easily with arithmetic operators.

Arithmetic Operators

Operator Description Example Result
+ Addition $a + $b Sum of $a and $b
- Subtraction $a - $b Difference
* Multiplication $a * $b Product
/ Division $a / $b Quotient
% Modulus $a % $b Remainder
** Exponentiation $a ** $b $a raised to $b

Example:

<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1
echo $a ** $b; // 1000
?>

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Example Equivalent To
= $x = 5 Assign 5 to $x
+= $x += 3 $x = $x + 3
-= $x -= 2 $x = $x - 2
*= $x *= 4 $x = $x * 4
/= $x /= 2 $x = $x / 2
.= $x .= "PHP" $x = $x . "PHP"

Example:

<?php
$x = 10;
$x += 5; // $x = 15
echo $x;
?>

5.3 Comparison and Logical Operators

Comparison and logical operators are used in conditional statements (like if and while) to compare values and control program flow.

Comparison Operators

Operator Description Example Result
== Equal $a == $b true if values are equal
=== Identical $a === $b true if values and types are equal
!= Not equal $a != $b true if values differ
!== Not identical $a !== $b true if values or types differ
> Greater than $a > $b true if $a > $b
< Less than $a < $b true if $a < $b
>= Greater or equal $a >= $b true if $a$b
<= Less or equal $a <= $b true if $a$b

Logical Operators

Operator Description Example
&& or and True if both are true $a && $b
` oror`
! Negation !$a (true if $a is false)

Example:

<?php
$age = 20;
if ($age >= 18 && $age <= 30) {
echo "You are a young adult.";
}
?>

Tip: Always use === and !== for strict comparison, especially when working with different data types.


5.4 Arrays and Array Functions

Arrays allow you to store multiple values under one variable name. PHP provides powerful functions for manipulating arrays.

Creating Arrays

<?php
$fruits = ["apple", "banana", "cherry"];
$person = ["name" => "Alice", "age" => 25];
?>

Accessing Array Elements

echo $fruits[1]; // banana
echo $person["name"]; // Alice

Useful Array Functions

Function Description Example Output
count() Counts elements count($fruits) 3
array_push() Adds an element array_push($fruits, "orange") Adds “orange”
array_pop() Removes last element array_pop($fruits) Removes “cherry”
array_merge() Merges arrays array_merge($a, $b) Combined array
in_array() Checks if value exists in_array("apple", $fruits) true
array_keys() Returns all keys array_keys($person) [“name”, “age”]

Example:

<?php
$colors = ["red", "green", "blue"];
array_push($colors, "yellow");
print_r($colors);
?>

5.5 Type Conversion Examples

PHP automatically converts data types when needed (type juggling), but you can also convert them manually (type casting).

Automatic Type Conversion (Type Juggling)

<?php
$x = "5"; // string
$y = 10; // integer
$sum = $x + $y; // "5" automatically converted to int
echo $sum; // 15
?>

Manual Type Casting

You can explicitly convert a variable’s type:

<?php
$price = "19.99";
$price = (float)$price;
var_dump($price); // float(19.99)
?>

Other casts include:

  • (int) or (integer)

  • (float) or (double)

  • (string)

  • (bool)

  • (array)

  • (object)

Converting Using Built-in Functions

intval("42"); // 42
floatval("10.5"); // 10.5
strval(123); // "123"
settype($x, "string");

6. PHP Type Declarations (PHP 7+)

Starting from PHP 7, the language introduced type declarations (also called type hints).
They allow developers to specify the expected data type for function parameters and return values.
This feature helps prevent type-related bugs, improves code readability, and makes applications more reliable.

PHP’s type declarations support both scalar types (like int, float, string, bool) and complex types (like array, object, callable, class names, and iterable).

Type declarations can be used in two places:

  1. Function or method parameters (input values).

  2. Function or method return values (output values).


6.1 Scalar Type Hints

Scalar type hints let you specify the type of data a function’s parameters should receive.
PHP will automatically try to convert the provided value to the correct type unless strict typing is enabled (explained later).

Supported Scalar Types

  • int — integer numbers

  • float — decimal numbers

  • string — text values

  • bool — true/false values

Example:

<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}

echo addNumbers(5, 10); // Outputs: 15
echo addNumbers(5, “7”); // Also works: “7” is converted to 7
?>

Here, both parameters $a and $b are expected to be integers.
Since PHP automatically converts "7" to an integer, the function runs successfully.

Without Correct Type:

If strict typing is enabled (see 6.3 below), PHP will throw a TypeError when you pass the wrong data type:

addNumbers("five", 10); // Fatal error in strict mode

Tip: Use scalar type hints to make your functions predictable and easier to debug.


6.2 Return Type Declarations

Return type declarations specify what type of value a function must return.
This ensures that the output matches the expected data type, preventing unexpected behavior.

Syntax:

function functionName(parameters): returnType {
// function body
}

Example 1:

<?php
function multiply(float $x, float $y): float {
return $x * $y;
}

echo multiply(2.5, 4); // Outputs: 10
?>

Here, the function must return a float. Even though one argument is an integer, the result is converted to a float.

Example 2 (string return type):

<?php
function greet(string $name): string {
return "Hello, " . $name;
}

echo greet(“Alice”); // Outputs: Hello, Alice
?>

If the function returns a value of a different type (e.g., an array instead of a string), PHP will raise a TypeError.

Tip: Always declare return types in modern PHP to improve code clarity and maintainability.


6.3 Strict Typing Mode

By default, PHP performs weak (coercive) typing, which means it automatically converts values to the required type when possible.
However, you can enable strict typing to make PHP enforce type declarations strictly — without automatic conversion.

How to Enable Strict Typing

Add the following line at the top of your PHP file, before any other code:

<?php
declare(strict_types=1);

When strict mode is enabled:

  • PHP does not convert data types automatically.

  • Passing a mismatched type causes a TypeError.

Example:

<?php
declare(strict_types=1);

function addNumbers(int $a, int $b): int {
return $a + $b;
}

echo addNumbers(5, “10”); // ❌ TypeError: Argument 2 must be of type int, string given
?>

Without strict mode (declare(strict_types=1); removed), the above code would work because PHP would convert "10" to an integer automatically.

When to Use Strict Typing:

  • In large applications where data integrity is critical.

  • When working in teams to ensure consistent function usage.

  • When using APIs or third-party libraries that expect strict type consistency.


Summary

Feature Description Example
Scalar Type Hints Define the expected parameter types (int, float, string, bool) function test(int $x)
Return Type Declarations Specify the expected return type of a function function sum(): int
Strict Typing Mode Enforces exact type matches (no automatic conversions) declare(strict_types=1);

Key Benefits:

  • Prevents unexpected type conversions.

  • Improves code readability and reliability.

  • Makes debugging easier.

  • Encourages cleaner, more maintainable code.

 

 

 

7. Common Mistakes and Best Practices

Even though PHP is beginner-friendly, it’s easy to make small mistakes that can lead to bugs, security issues, or poor performance.
This section highlights common pitfalls and offers best practices to help you write clean, maintainable, and error-free PHP code.


7.1 Avoiding Undefined Variables

In PHP, you can use variables without declaring them first — but if you try to access a variable that hasn’t been defined, PHP will throw a notice:

“Notice: Undefined variable”

This often happens when variables are used inside conditions, loops, or forms without checking if they exist.

Example of a common mistake:

<?php
echo $username; // Undefined variable if not set earlier
?>

Better approach:

Always check whether a variable exists before using it.

<?php
if (isset($username)) {
echo $username;
} else {
echo "Guest";
}
?>

Alternatively, use the null coalescing operator (??) introduced in PHP 7:

<?php
echo $username ?? "Guest"; // Outputs "Guest" if $username is not set
?>

Best Practice:

  • Always initialize your variables before use.

  • Use isset() or empty() to avoid undefined variable errors.

  • For forms, use the null coalescing operator with $_POST or $_GET, e.g.:

    $email = $_POST['email'] ?? '';

7.2 Understanding Type Juggling Pitfalls

PHP is a loosely typed language, meaning it automatically converts between data types when necessary.
While convenient, this type juggling can lead to unexpected results if you’re not careful.

Example of unexpected behavior:

<?php
var_dump(0 == "abc"); // true (because "abc" becomes 0)
var_dump("123abc" == 123); // true (string converted to number)
?>

Here, PHP converts strings to numbers automatically, which can cause logic errors.

Best Practices to Avoid Type Juggling Issues:

  1. Use strict comparison operators (=== and !==)
    These check both value and type:

    <?php
    var_dump(0 === "0"); // false (different types)
    ?>
  2. Enable strict typing when possible:

    <?php
    declare(strict_types=1);
    ?>
  3. Validate and sanitize input data (especially from users) before processing.

  4. Be cautious when comparing numbers and strings — always cast explicitly if needed:

    (int)$value; (string)$id;

Key takeaway:
Type juggling can simplify code but may cause unpredictable results — prefer strict comparisons and explicit casting to avoid subtle bugs.


7.3 Using Constants for Configuration

Constants are variables whose values cannot change after being defined.
They’re ideal for storing configuration settings such as database credentials, API keys, or fixed values used across your application.

Example:

<?php
define("SITE_NAME", "MyWebsite");
define("VERSION", "1.0");
echo SITE_NAME; // Outputs: MyWebsite
?>

Using const:

You can also define constants using the const keyword (commonly used in classes):

<?php
class Config {
const DB_HOST = "localhost";
const DB_USER = "root";
}

echo Config::DB_HOST; // Outputs: localhost
?>

Best Practice:

  • Store constants in a separate configuration file (config.php).

  • Use uppercase for constant names (e.g., MAX_USERS, API_URL).

  • Never store sensitive information (like passwords or keys) directly in public code — instead, use environment variables or .env files.


7.4 Writing Readable and Maintainable Code

Readable code is easier to debug, extend, and collaborate on — even months after you wrote it.
Following good coding practices makes your PHP applications more professional and scalable.

Best Practices for Readability:

  1. Use clear and descriptive variable names

    $totalPrice = $price * $quantity; // Clear and self-explanatory
  2. Indent and format your code properly

    if ($age >= 18) {
    echo "Adult";
    } else {
    echo "Minor";
    }
  3. Comment your code

    • Use comments to explain why something is done, not what is done.

    • Example:

      // Apply discount if user is a premium member
  4. Follow consistent naming conventions

    • Variables: $camelCase

    • Constants: UPPER_CASE

    • Functions: snake_case() or camelCase() depending on your style guide.

  5. Organize code into functions or classes

    • Avoid repeating the same code — use reusable functions.

    • Example:

      function calculateTotal($price, $qty) {
      return $price * $qty;
      }
  6. Enable error reporting during development

    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    This helps you catch mistakes early.

Tip: Always write code as if someone else will have to read and maintain it — because often, someone will (even if it’s future you).


Summary

Common Issue Problem Best Practice
Undefined variables Causes notices and logic errors Initialize variables, use isset() or ??
Type juggling Leads to unexpected comparisons Use ===, !==, and strict typing
Hardcoded config values Difficult to update or maintain Use constants or config files
Unreadable code Hard to debug and extend Use clear names, indentation, and comments

Key Takeaways:

  • Write clean, consistent, and well-documented code.

  • Avoid relying on PHP’s loose typing.

  • Keep configuration values centralized and secure.

  • Always prioritize clarity and maintainability.

 

 

 

8. Summary and Key Takeaways

This section brings together all the essential concepts you’ve learned about PHP’s syntax, variables, and data types.
Understanding these fundamentals is crucial for writing correct, readable, and efficient PHP code — the foundation of any web application.


8.1 PHP Syntax Recap

  • Every PHP script starts with <?php and ends with ?>.

  • Statements end with a semicolon (;).

  • PHP code can be embedded inside HTML for dynamic web pages.

  • Comments are used to explain code:

    // Single-line comment
    /* Multi-line comment */

Key Point:
Keep your syntax clean and consistent — even small errors like missing semicolons can cause script failures.


8.2 Variables in PHP

  • Variables in PHP start with a $ sign and are case-sensitive.
    Example: $name, $Name, and $NAME are all different variables.

  • Variables must start with a letter or underscore (_), not a number.

  • You assign values using the = operator:

    $age = 25;
    $city = "London";
  • PHP is loosely typed, so you don’t need to declare the type — PHP decides it automatically based on the value.

Best Practice:
Always use meaningful variable names (e.g., $totalPrice, not $tp).


8.3 Data Types Overview

PHP supports eight main data types, grouped as follows:

Category Data Types Description
Scalar int, float, string, bool Simple values like numbers, text, true/false
Compound array, object Collections or structures containing multiple values
Special NULL, resource Special-purpose types for empty or external data

Example:

<?php
$age = 30; // Integer
$price = 19.99; // Float
$name = "Alice"; // String
$isAdmin = true; // Boolean
$colors = ["red", "blue"]; // Array
?>

8.4 Type Declarations (PHP 7+)

  • You can define parameter and return types in functions:

    function addNumbers(int $a, int $b): int {
    return $a + $b;
    }
  • Enable strict typing with:

    declare(strict_types=1);

    This prevents PHP from converting types automatically, making your code more reliable.

Tip: Use strict typing in modern PHP projects to catch type-related errors early.


8.5 Common Mistakes and Best Practices

  1. Undefined Variables:
    Always check with isset() or use the null coalescing operator (??).

  2. Type Juggling:
    Avoid unexpected conversions by using strict comparison operators (===, !==).

  3. Constants for Configuration:
    Store configuration data (like database info) in constants or environment files, not directly in code.

  4. Readable Code:

    • Use descriptive variable names.

    • Format and indent properly.

    • Comment only when necessary.

    • Use reusable functions instead of repeating code.

Golden Rule:
Write code that is easy for others (and your future self) to understand.


8.6 Final Thoughts

By mastering PHP’s syntax, variables, and data types, you’ve learned the core building blocks of PHP programming.
These concepts form the basis for more advanced topics such as:

  • Control structures (loops, conditionals)

  • Functions and object-oriented programming

  • Working with forms and databases

  • Error handling and debugging

Key Takeaways:

  • PHP is flexible but requires disciplined coding habits.

  • Always write readable, maintainable, and type-safe code.

  • Practice frequently — the best way to learn PHP is by building small projects.

 

 

 

9. Hands-On Exercises and Practice Questions

Practice is essential to solidify your understanding of PHP syntax, variables, and data types. This section provides exercises that gradually increase in difficulty, from simple syntax checks to working with variables, arrays, and functions.


9.1 Getting Started Exercises

These exercises help you practice basic syntax and output:

  1. Write a PHP script that prints your name and age.

  2. Create a script using single and double quotes and observe the difference in variable interpolation.

  3. Add comments (single-line and multi-line) to your PHP file explaining each line of code.

Goal: Get comfortable with PHP tags, semicolons, output statements, and comments.


9.2 Variables and Data Types Exercises

Practice creating and manipulating variables:

  1. Declare variables for your first name, last name, and age. Print a sentence introducing yourself using concatenation.

  2. Create three variables: an integer, a float, and a string. Display their values and use var_dump() to show their types.

  3. Use a boolean variable to store whether a user is logged in. Write a conditional statement that prints a different message based on its value.

  4. Experiment with NULL: create a variable, assign NULL, and check if it is null using is_null().

Goal: Understand variable declaration, data types, and basic operations with them.


9.3 Arrays and Compound Data Types Exercises

Practice working with arrays and objects:

  1. Create an indexed array of your five favorite fruits and print the third fruit.

  2. Create an associative array representing a person with keys name, age, and city. Print each value separately.

  3. Add a new fruit to your indexed array and remove the last one using array functions.

  4. Create a simple class Car with properties brand and color, and a method to display them. Create an object and call the method.

Goal: Learn how to store, access, and manipulate multiple values using arrays and objects.


9.4 Operators and Type Conversion Exercises

Practice arithmetic, logical, and comparison operations:

  1. Create two numeric variables and calculate their sum, difference, product, division, and modulus.

  2. Create two variables with string numbers (e.g., "10" and "5") and add them. Use var_dump() to see the type.

  3. Compare two variables using == and ===. Observe the difference.

  4. Convert a string variable containing a number into an integer and perform an arithmetic operation.

Goal: Gain confidence using operators and type conversion in PHP.


9.5 Functions and Type Declarations Exercises

Practice using functions and type declarations (PHP 7+):

  1. Write a function that takes two integers as parameters and returns their sum. Use a return type declaration.

  2. Write a function that takes a string parameter and returns it in uppercase.

  3. Enable strict typing (declare(strict_types=1);) and test your function with correct and incorrect data types.

  4. Write a function that calculates the area of a rectangle (length × width) and ensure the return type is float.

Goal: Understand functions, parameter types, return types, and strict typing.


9.6 Bonus Challenge Exercises

  1. Create a simple script that combines all you’ve learned:

    • Store your favorite movies in an array.

    • Create a function that prints each movie with its index.

    • Use a boolean variable to check if you want to print the list.

  2. Create a configuration file with constants for your site name, version, and admin email. Include this file in another script and print the constants.

  3. Build a small calculator script that asks for two numbers and an operation (+, -, *, /) and outputs the result using functions.

Goal: Reinforce learning by building mini-projects that integrate multiple concepts.


9.7 Tips for Practice

  • Test your scripts frequently using a local server (like XAMPP, WAMP, or MAMP).

  • Use var_dump() and print_r() to inspect variables while learning.

  • Experiment: change values, data types, or array structures to see how PHP behaves.

  • Keep your code clean and well-commented — it helps in debugging and understanding later.

Key Takeaway: Hands-on practice is the fastest way to master PHP. Start with simple exercises, then gradually combine concepts to build small projects.