Chapter 2 - PHP Fundamentals
Chapter 2 - PHP Fundamentals
Chapter 2
PHP SYNTAX and BASIC CONCEPTS
Introduction
PHP, which stands for "Hypertext Preprocessor", is a widely-used server-side scripting language designed
primarily for web development. It was initially created by Rasmus Lerdorf in 1993 and has since evolved
into a powerful tool that powers millions of websites and web applications worldwide. Unlike client-side
languages like JavaScript, which execute code on the user's browser, PHP runs on the server, processes
the script, and sends the resulting HTML output to the client. This ensures better security, as the actual
PHP code remains hidden from users.
PHP is open-source and continuously improved by a large community of developers. The latest version,
PHP 8.4, released in November 2024, introduces significant performance enhancements, improved error
handling, and new features for modern web development. Due to its simplicity, flexibility, and efficiency,
PHP remains one of the most popular programming languages for building dynamic and interactive
websites, content management systems (CMS), and web applications.
Characteristics of PHP
PHP offers numerous features that make it an essential tool for web developers:
Versatile File Structure: PHP files can contain a mix of HTML, CSS, JavaScript, and PHP code,
making it easy to integrate with front-end technologies.
Dynamic Content Generation: PHP allows websites to generate dynamic content, such as
displaying personalized information, handling user input, and updating page content in real time.
Database Connectivity: PHP supports various databases (MySQL, PostgreSQL, SQLite, etc.),
making it easy to build database-driven web applications.
User Authentication and Access Control: PHP enables secure user authentication and role-based
access control, ensuring that sensitive data is protected.
File Handling Capabilities: PHP provides built-in functions for reading, writing, modifying, and
deleting files on the server.
1 of 19
Internet Programming II
Cross-Platform Compatibility: PHP runs on multiple operating systems, including Windows, Linux,
macOS, and Unix, and is compatible with almost all web servers, such as Apache and Nginx.
Dynamic Typing and Flexibility: PHP is dynamically typed, meaning variables do not require explicit
type declarations. This makes it easy to work with different data types without strict constraints.
Security Features: PHP includes built-in features for encryption, data validation, session
management, and protection against SQL injection and XSS attacks.
Fast and Efficient: PHP executes code quickly and efficiently, with modern versions significantly
improving performance.
Active Community and Documentation: Being open-source, PHP has extensive documentation
and a large developer community, making it easy to find support, tutorials, and libraries for
various applications.
<?php
echo "Hello, PHP World!";
?>
PHP can also be mixed with HTML:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to PHP</h1>
<?php
echo "Today is " . date("l") . "!";
?>
</body>
</html>
2 of 19
Internet Programming II
Comments in PHP
Comments help explain the code and are ignored during execution. PHP supports single-line and multi-
line comments.
Single-line comments:
Multi-line comments:
/*
This is a multi-line comment.
It spans multiple lines.
Useful for explaining complex code.
*/
Both echo and print are used to output data to the browser.
The key difference between echo and print is that echo can output multiple values, while print
returns a value (1), making it slightly slower.
Practice Exercises
Modify the example code to display your name dynamically. Use comments to explain each line of your
code. Try using both echo and print in the same script.
By practicing these exercises, you will develop a strong understanding of PHP syntax and basic concepts.
3 of 19
Internet Programming II
1. User Request: A user requests a PHP page by entering a URL in their browser (e.g.,
http://example.com/index.php).
2. Server Processing: The web server (e.g., Apache, Nginx, IIS) receives the request and forwards it
to the PHP interpreter for execution.
3. PHP Script Execution: The PHP engine processes the script, which may include:
Retrieving data from a database (e.g., MySQL, PostgreSQL).
Handling user input (e.g., form submissions, session management).
Performing calculations or logical operations.
Generating dynamic HTML content.
4. HTML Output Generation: PHP generates plain HTML output, which is sent back to the client’s
browser for rendering.
5. Client-Side Display: The browser displays the final web page, but the actual PHP code remains
hidden, ensuring security and confidentiality.
4 of 19
Internet Programming II
Example:
$name = "John";
$age = 25;
$price = 19.99;
$isAvailable = true;
Variable names in PHP must start with a letter or an underscore and cannot contain spaces. They are case-
sensitive, meaning $name and $Name are considered different variables.
$var = "123";
$int_var = (int)$var; // Converts string to integer
intval(), floatval(), and boolval() functions can also be used for type conversion.
5 of 19
Internet Programming II
PHP Constants
Constants store fixed values that cannot be changed during script execution.
Declared using:
define("SITE_NAME", "MyWebsite");
define("PI", 3.1416);
echo PI; // Output: 3.1416
Practice Exercises
1. Declare variables of different data types and print their values.
2. Experiment with type juggling by performing operations between different data types.
3. Use type casting to convert a float to an integer and observe the results.
Operators in PHP
Operators in PHP are used to perform operations on variables and values. This section covers different
types of operators, including arithmetic, comparison, logical, assignment, and string operators.con
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values.
Example:
$x = 10;
$y = 3;
echo $x + $y; // Output: 13
6 of 19
Internet Programming II
Comparison Operators
Comparison operators compare two values and return a boolean (true or false).
== Equal to $a == $b
!= Not equal $a != $b
Example:
$a = 5;
$b = 10;
var_dump($a < $b); // Output: true
Logical Operators
Logical operators are used to combine multiple conditions.
|| OR $a || $b
! NOT !$a
Example:
$a = true;
$b = false;
var_dump($a && $b); // Output: false
7 of 19
Internet Programming II
Assignment Operators
Assignment operators are used to assign values to variables.
= $a = $b $a = $b
+= $a += $b $a = $a + $b
-= $a -= $b $a = $a - $b
*= $a *= $b $a = $a * $b
/= $a /= $b $a = $a / $b
%= $a %= $b $a = $a % $b
Example:
$x = 5;
$x += 3; // Equivalent to $x = $x + 3
String Operators
String operators are used to manipulate text values.
. Concatenation $a . $b
.= Append $a .= $b
Example:
Practice Exercises
1. Perform arithmetic operations on two variables and print the results.
2. Use comparison operators to compare values and display the output.
3. Write a script using logical operators to evaluate multiple conditions.
4. Concatenate two strings and display the output.
8 of 19
Internet Programming II
Conditional Statements
Conditional statements allow execution of specific code blocks based on given conditions. PHP provides
several ways to handle conditions: if, if...else, if...elseif...else, and switch.
1. if Statement
The if statement executes a block of code only if a specified condition evaluates to true.
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
2. if...else Statement
The if...else statement runs one block of code if the condition is true, and another if it is false.
$marks = 50;
if ($marks >= 50) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}
3. if...elseif...else Statement
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
9 of 19
Internet Programming II
} else {
echo "Grade: F";
}
4. switch Statement
The switch statement is used to compare a variable against multiple values.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week.";
break;
case "Friday":
echo "Weekend is coming!";
break;
default:
echo "Another regular day.";
}
Loop Structures
Loops allow execution of a block of code multiple times until a condition is met. PHP provides several
looping structures: for, while, do...while, and foreach.
1. for Loop
The for loop is used when the number of iterations is known beforehand.
2. while Loop
The while loop executes a block of code as long as the specified condition is true.
$count = 1;
while ($count <= 5) {
echo "Count: $count <br>";
$count++;
}
10 of 19
Internet Programming II
3. do...while Loop
This loop executes the block at least once before checking the condition.
$num = 1;
do {
echo "Number: $num <br>";
$num++;
} while ($num <= 5);
Practice Exercises
1. Write a script using if...elseif...else to assign grades based on marks.
2. Use a switch statement to display messages for different days of the week.
3. Implement a for loop to print numbers from 1 to 10.
4. Create a while loop to print even numbers between 1 and 20.
5. Iterate through an associative array using a foreach loop and display key-value pairs.
Defining a Function
function greet() {
echo "Hello, welcome to PHP!";
}
In this example, calling greet(); will output "Hello, welcome to PHP!".
11 of 19
Internet Programming II
Calling a Function
Once defined, a function is executed when it is called:
greet();
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("John");
Here, the function greetUser("John"); outputs "Hello, John!".
12 of 19
Internet Programming II
1. Local Scope
Variables declared inside a function are local and cannot be accessed outside it.
function localScope() {
$message = "This is a local variable";
echo $message;
}
localScope();
// echo $message; // This will cause an error
2. Global Scope
Variables declared outside a function have global scope and cannot be accessed inside a function unless
explicitly specified using the global keyword.
3. Static Scope
Static variables retain their value across multiple function calls.
function staticCounter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
staticCounter(); // Outputs: 1
staticCounter(); // Outputs: 2
staticCounter(); // Outputs: 3
13 of 19
Internet Programming II
Passing Arguments
By default, PHP passes arguments by value, meaning changes made inside the function do not affect the
original variable. Passing by reference allows modifications to persist outside the function.
function increment($num) {
$num++;
echo "Inside function: $num";
}
$value = 5;
increment($value);
echo "Outside function: $value"; // Outputs: Outside function: 5
The original $value remains unchanged.
6. Passing by Reference
Using the & symbol allows functions to modify the original variable.
function incrementByReference(&$num) {
$num++;
}
$value = 5;
incrementByReference($value);
echo "Outside function: $value"; // Outputs: Outside function: 6
14 of 19
Internet Programming II
String Functions
strlen("Hello World"); // Returns length of the string
strtoupper("hello"); // Converts to uppercase
strtolower("HELLO"); // Converts to lowercase
str_replace("world", "PHP", "Hello world"); // Replaces text
trim(" text "); // Removes whitespace from both sides
Mathematical Functions
abs(-5); // Returns absolute value (5)
round(4.6); // Rounds to nearest integer (5)
rand(1, 100); // Generates a random number between 1 and 100
max(10, 20, 30); // Returns the largest number (30)
min(10, 20, 30); // Returns the smallest number (10)
Practice Exercises
1. Create a function to add a new business listing – The function should take business name,
category, and location as parameters and return a confirmation message.
2. Write a function to search for businesses by category – The function should accept a category as
an argument and return a filtered list of businesses.
3. Implement a function to calculate the number of businesses per city – Use an array to store
businesses and group them by city.
4. Develop a function to update business information – The function should accept a business ID
and an associative array of updated details.
5. Pass business data by reference to optimize memory usage – Modify a business listing inside a
function using reference arguments.
15 of 19
Internet Programming II
PHP Arrays
Arrays are fundamental data structures in PHP that allow multiple values to be stored in a single variable.
Arrays help in organizing and manipulating data efficiently, making them essential for dynamic web
applications, such as a Business Directory Application.
1. Indexed Arrays
Indexed arrays store values using numeric indexes that start from zero.
2. Associative Arrays
Associative arrays use named keys instead of numeric indexes, making them ideal for structured data like
business listings.
$business = [
"name" => "Cafe Aroma",
"category" => "Restaurant",
"location" => "Downtown"
];
echo $business["name"]; // Outputs: Cafe Aroma
Using a foreach loop to iterate over an associative array:
16 of 19
Internet Programming II
3. Multidimensional Arrays
Multidimensional arrays contain multiple arrays inside them, useful for storing complex data structures
like a list of businesses with details.
$directory = [
["name" => "Cafe Aroma", "category" => "Restaurant", "location" =>
"Downtown"],
["name" => "Tech Solutions", "category" => "IT Services", "location" =>
"Uptown"],
["name" => "Green Market", "category" => "Grocery", "location" =>
"Suburb"]
];
echo $directory[1]["name"]; // Outputs: Tech Solutions
Iterating through a multidimensional array:
17 of 19
Internet Programming II
18 of 19
Internet Programming II
Practice Exercises
1. Store a list of business names as an indexed array and display them in a dropdown menu for users to
select.
2. Use an associative array to store business details (name, category, location, contact number) and
display them in a structured format.
3. Implement a search function that takes a category as input and filters businesses in that category.
4. Sort business listings alphabetically by name and display them in a user-friendly table format.
5. Group businesses by location using multidimensional arrays and display businesses grouped under
each city.
6. Create a function to update business details by modifying values in an associative array.
7. Use array_column() to extract all business names from the directory and display them as a simple
list.
8. Remove duplicate business entries using array_unique() and display only unique businesses.
9. Use array_chunk() to paginate business listings and show only a limited number of businesses per
page.
10. Check if a business is already listed before adding it to the directory using in_array() and provide
appropriate feedback to users.
19 of 19