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:
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:
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:
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:
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):
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:
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:
Here, $Name is undefined because PHP treats it as a different variable from $name.
However, in the case of functions:
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:
Invalid identifiers:
✅ 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:
Using print
-
Can output only one string at a time.
-
Returns the value
1, so it can be used in expressions.
Example:
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:
Output:
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:
Here:
-
$nameholds a string value ("Alice"), -
$ageholds an integer, -
$priceholds 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:
-
Variable names must start with a dollar sign ($).
-
The first character after
$must be a letter or underscore (_). -
Variable names can contain letters, numbers, and underscores only (no spaces or special characters).
-
Variable names are case-sensitive (
$Nameand$nameare different variables).
Examples of valid variable names:
Invalid variable names:
✅ 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:
You can also assign one variable to another:
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.
Global Variables
Declared outside of all functions and accessible throughout the script, except inside functions (unless declared as global).
Static Variables
A static variable retains its value even after the function ends.
It is initialized only once.
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. -
$_SESSIONand$_COOKIE– Manage session and cookie data. -
$_FILES– Handles file uploads. -
$_REQUEST– Contains data from GET, POST, and COOKIE.
Example:
3.5 Variable Variables ($$var)
PHP allows you to create variable variables, where the value of one variable determines the name of another.
Example:
echo $color; // Outputs: blue
Explanation:
-
$varNamecontains the string"color". -
$$varNamebecomes$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()
Using const (from PHP 5.3+)
Differences:
-
define()works only at runtime, whileconstis 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:
-
Scalar types – represent a single value (e.g., integer, float, string, boolean)
-
Compound types – can contain multiple values (e.g., array, object)
-
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:
Difference between single and double quotes:
-
Single quotes display text as-is.
-
Double quotes parse variables and escape sequences (like
\nfor a new line).
Integer
An integer is a whole number (positive, negative, or zero) without a decimal point.
Example:
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:
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:
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):
Example (Associative Array):
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:
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:
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:
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:
You can also manually convert a variable’s type using type casting:
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.
gettype()
Returns only the type of the variable as a string.
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:
The . operator connects strings together. You can also append a string using .=:
String Interpolation
If you use double quotes, PHP can insert variable values directly into strings.
Note: Single quotes ' ' will not interpret variables inside the string.
Useful String Functions
PHP provides many built-in string functions:
✅ 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:
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:
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:
✅ 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
Accessing Array Elements
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:
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)
Manual Type Casting
You can explicitly convert a variable’s type:
Other casts include:
-
(int)or(integer) -
(float)or(double) -
(string) -
(bool) -
(array) -
(object)
Converting Using Built-in Functions
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:
-
Function or method parameters (input values).
-
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:
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:
✅ 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:
Example 1:
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):
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:
When strict mode is enabled:
-
PHP does not convert data types automatically.
-
Passing a mismatched type causes a TypeError.
Example:
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:
Better approach:
Always check whether a variable exists before using it.
Alternatively, use the null coalescing operator (??) introduced in PHP 7:
✅ Best Practice:
-
Always initialize your variables before use.
-
Use
isset()orempty()to avoid undefined variable errors. -
For forms, use the null coalescing operator with
$_POSTor$_GET, e.g.:
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:
Here, PHP converts strings to numbers automatically, which can cause logic errors.
Best Practices to Avoid Type Juggling Issues:
-
Use strict comparison operators (
===and!==)
These check both value and type: -
Enable strict typing when possible:
-
Validate and sanitize input data (especially from users) before processing.
-
Be cautious when comparing numbers and strings — always cast explicitly if needed:
✅ 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:
Using const:
You can also define constants using the const keyword (commonly used in classes):
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
.envfiles.
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:
-
Use clear and descriptive variable names
-
Indent and format your code properly
-
Comment your code
-
Use comments to explain why something is done, not what is done.
-
Example:
-
-
Follow consistent naming conventions
-
Variables:
$camelCase -
Constants:
UPPER_CASE -
Functions:
snake_case()orcamelCase()depending on your style guide.
-
-
Organize code into functions or classes
-
Avoid repeating the same code — use reusable functions.
-
Example:
-
-
Enable error reporting during development
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
<?phpand ends with?>. -
Statements end with a semicolon (
;). -
PHP code can be embedded inside HTML for dynamic web pages.
-
Comments are used to explain code:
✅ 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$NAMEare all different variables. -
Variables must start with a letter or underscore (
_), not a number. -
You assign values using the
=operator: -
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:
8.4 Type Declarations (PHP 7+)
-
You can define parameter and return types in functions:
-
Enable strict typing with:
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
-
Undefined Variables:
Always check withisset()or use the null coalescing operator (??). -
Type Juggling:
Avoid unexpected conversions by using strict comparison operators (===,!==). -
Constants for Configuration:
Store configuration data (like database info) in constants or environment files, not directly in code. -
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:
-
Write a PHP script that prints your name and age.
-
Create a script using single and double quotes and observe the difference in variable interpolation.
-
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:
-
Declare variables for your first name, last name, and age. Print a sentence introducing yourself using concatenation.
-
Create three variables: an integer, a float, and a string. Display their values and use
var_dump()to show their types. -
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.
-
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:
-
Create an indexed array of your five favorite fruits and print the third fruit.
-
Create an associative array representing a person with keys
name,age, andcity. Print each value separately. -
Add a new fruit to your indexed array and remove the last one using array functions.
-
Create a simple class
Carwith propertiesbrandandcolor, 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:
-
Create two numeric variables and calculate their sum, difference, product, division, and modulus.
-
Create two variables with string numbers (e.g.,
"10"and"5") and add them. Usevar_dump()to see the type. -
Compare two variables using
==and===. Observe the difference. -
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+):
-
Write a function that takes two integers as parameters and returns their sum. Use a return type declaration.
-
Write a function that takes a string parameter and returns it in uppercase.
-
Enable strict typing (
declare(strict_types=1);) and test your function with correct and incorrect data types. -
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
-
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.
-
-
Create a configuration file with constants for your site name, version, and admin email. Include this file in another script and print the constants.
-
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()andprint_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.
