Web TechnologyUnit 812 min read
PHP Basics, Arrays, Functions & OOP
Unit 8 of Web Technology covers PHP syntax, data structures (arrays), reusable code (functions), and object-oriented programming (classes/objects) with practical examples, validation logic, and real-world applications like eSewa’s user authentication and Daraz’s product catalogs.
TAKEAWAYS:
- PHP is a server-side scripting language embedded in HTML to process form data, validate inputs, and generate dynamic content.
- Arrays store multiple values in a single variable (indexed, associative, or multidimensional) and are essential for handling lists (e.g., user hobbies, product inventories).
- Functions encapsulate reusable logic (e.g., form validation, calculations) and reduce code duplication.
- OOP in PHP uses classes/objects to model real-world entities (e.g.,
User,Order) with properties and methods, improving maintainability. - Cookies and sessions manage persistent data across page requests (e.g., shopping carts, user logins).
- JSON and PHP arrays often interchange for API data (e.g., Daraz’s product search results).
1. Introduction to PHP
PHP (Hypertext Preprocessor) is a server-side scripting language embedded in HTML to create dynamic web pages. Unlike JavaScript (client-side), PHP executes on the server before sending HTML to the browser. Key features:
- Platform-independent: Runs on Linux/Windows with Apache/Nginx.
- Database integration: Works seamlessly with MySQL, PostgreSQL, etc.
- Form processing: Validates and handles user inputs (e.g., login forms).
sequenceDiagram
participant User
participant Browser
participant Server
participant PHP
participant Database
User->>Browser: Sends HTTP request (e.g., form submission)
Browser->>Server: POSTs data to `process.php`
Server->>PHP: Executes PHP script
PHP->>Database: Queries/updates data (e.g., user login)
PHP->>Server: Returns dynamic HTML
Server->>Browser: Sends HTML response
Browser->>User: Displays result (e.g., dashboard)
note right of Browser: **PHP executes server-side, unlike JavaScript**PHP execution flow for a login form (e.g., Daraz account)How PHP Works
sequenceDiagram
participant User
participant Browser
participant Server
participant PHP
participant Database
User->>Browser: Sends HTTP request (e.g., form submission)
Browser->>Server: POSTs data to `process.php`
Server->>PHP: Executes PHP script
PHP->>Database: Queries/updates data
PHP->>Server: Returns dynamic HTML
Server->>Browser: Sends HTML response
Browser->>User: Displays resultReal Picture
2. PHP Syntax Basics
PHP code is enclosed in <?php ... ?> tags and mixed with HTML.
Variables
- Naming rules: Start with
$, case-sensitive ($name≠$Name). - Data types:
string,int,float,bool,array,object. - Example:
$name = "Rohan"; // String $age = 20; // Integer $isStudent = true; // Boolean echo $name . " is " . $age . " years old."; // Output: Rohan is 20 years old.
Operators
| Type | Example | Description |
|---|---|---|
| Arithmetic | $sum = $a + $b |
Addition, subtraction, etc. |
| Comparison | $x == $y |
Equality, inequality |
| Logical | !$isLoggedIn |
AND (&&), OR (` |
| Assignment | $total *= 2 |
Multiplies and assigns |
3. Arrays in PHP
Arrays store multiple values in one variable. Three types:
a) Indexed Arrays
- Numeric keys (auto-incremented from 0).
- Example: List of fruits.
$fruits = array("Apple", "Banana", "Mango"); echo $fruits[1]; // Output: Banana
b) Associative Arrays
- Named keys (e.g.,
["name"] => "Rohan"). - Example: User profile.
$user = array( "name" => "Rohan", "email" => "rohan@example.com", "age" => 20 ); echo $user["email"]; // Output: rohan@example.com
c) Multidimensional Arrays
- Arrays within arrays.
- Example: Product catalog (Daraz-style).
$products = array( array("id" => 1, "name" => "Laptop", "price" => 50000), array("id" => 2, "name" => "Phone", "price" => 20000) ); echo $products[0]["name"]; // Output: Laptop
Common Array Functions
| Function | Example | Description |
|---|---|---|
count() |
count($fruits) |
Returns array length. |
array_push() |
array_push($fruits, "Grape") |
Adds an element. |
implode() |
implode(", ", $fruits) |
Converts array to string. |
in_array() |
in_array("Banana", $fruits) |
Checks if value exists. |
Worked Example: Book Search Catalog (Like Daraz)
$books = array(
array("title" => "PHP for Beginners", "author" => "John Doe", "price" => 1500),
array("title" => "Web Design", "author" => "Jane Smith", "price" => 2000)
);
// Search by title
function searchBooks($books, $keyword) {
$results = array();
foreach ($books as $book) {
if (stripos($book["title"], $keyword) !== false) {
array_push($results, $book);
}
}
return $results;
}
$results = searchBooks($books, "PHP");
print_r($results);
Output:
Array ( [0] => Array ( [title] => PHP for Beginners ... ) )
4. Functions in PHP
Functions encapsulate reusable code. Syntax:
function functionName($param1, $param2) {
// Code
return $result;
}
Example: Product Discount Calculator
function calculateDiscount($price, $discountPercent) {
$discount = $price * ($discountPercent / 100);
return $price - $discount;
}
$finalPrice = calculateDiscount(5000, 10); // 4500
echo "Discounted Price: $" . $finalPrice;
Predefined Functions
| Function | Example | Description |
|---|---|---|
strtolower() |
strtolower("HELLO") |
Converts to lowercase. |
date() |
date("Y-m-d") |
Current date/time. |
file_get_contents() |
file_get_contents("data.txt") |
Reads a file. |
5. Object-Oriented Programming (OOP) in PHP
OOP models real-world entities as classes (blueprints) and objects (instances).
classDiagram
class User {
+String name
+String email
+greet() String
}
class Admin {
+String role
+banUser() void
}
User <|-- Admin
note for User "Example: $user = new User('Rohan', 'rohan@example.com');"Inheritance: Admin extends User (e.g., Daraz seller dashboard)
Key Concepts
- Class: Template for objects.
class User { // Properties public $name; public $email; // Method public function greet() { return "Hello, " . $this->name; } } - Object: Instance of a class.
$user = new User(); $user->name = "Rohan"; $user->email = "rohan@example.com"; echo $user->greet(); // Output: Hello, Rohan - Constructor: Special method to initialize objects.
class User { public function __construct($name, $email) { $this->name = $name; $this->email = $email; } } $user = new User("Rohan", "rohan@example.com");
Inheritance
- Parent class: Base class (e.g.,
Animal). - Child class: Inherits properties/methods (e.g.,
DogextendsAnimal).class Animal { public function eat() { return "Eating..."; } } class Dog extends Animal { public function bark() { return "Barking!"; } } $dog = new Dog(); echo $dog->eat(); // Output: Eating... echo $dog->bark(); // Output: Barking!
Real-World Example: eSewa User System
classDiagram
class User {
+String name
+String email
+greet() String
}
class Admin {
+approvePayment()
}
User <|-- AdminUserclass: Stores name/email, providesgreet().Adminclass: ExtendsUserand addsapprovePayment()for eSewa transactions.
6. Cookies and Sessions
Cookies
- Small data stored on the client’s browser.
- Example: Remembering a user’s language preference.
// Set cookie (expires in 1 hour) setcookie("language", "nepali", time() + 3600); // Retrieve cookie if (isset($_COOKIE["language"])) { echo "Language: " . $_COOKIE["language"]; }
Sessions
- Server-side storage for user-specific data (e.g., shopping carts).
- Example: Pathao’s ride tracking.
// Start session session_start(); // Store data $_SESSION["cart"] = array("item1", "item2"); // Retrieve data print_r($_SESSION["cart"]);
Comparison
| Feature | Cookies | Sessions |
|---|---|---|
| Storage | Client-side (browser) | Server-side |
| Security | Vulnerable to XSS attacks | More secure |
| Use Case | Preferences, tracking | User logins, carts |
7. JSON in PHP
JSON (JavaScript Object Notation) is a lightweight data format for APIs (e.g., Daraz’s product data).
PHP ↔ JSON Conversion
// Array to JSON
$data = array("name" => "Rohan", "age" => 20);
$json = json_encode($data);
echo $json; // Output: {"name":"Rohan","age":20}
// JSON to Array
$json = '{"name":"Rohan","age":20}';
$data = json_decode($json, true);
print_r($data); // Output: Array ( [name] => Rohan ... )
Example: API Response (Like NEPSE Stock Data)
$stockData = array(
"symbol" => "NEPSE",
"price" => 2500.50,
"change" => "+1.2%"
);
echo json_encode($stockData);
Output:
{"symbol":"NEPSE","price":2500.5,"change":"+1.2%"}
In the Real World
eSewa (Nepal)
- PHP + OOP: The backend uses PHP classes to model
User,Transaction, andPaymentobjects. When you pay a bill, PHP validates inputs (e.g., account number) and processes the transaction via a database. - Cookies: Store your login status to avoid repeated authentication.
- PHP + OOP: The backend uses PHP classes to model
Daraz (Nepal)
- Arrays: Product catalogs are stored as multidimensional arrays (e.g.,
$products[id][name][price]). PHP loops through these arrays to display search results. - JSON: API responses (e.g., product details) are sent as JSON, which PHP decodes into arrays for display.
- Arrays: Product catalogs are stored as multidimensional arrays (e.g.,
Khalti (Nepal)
- Sessions: Maintain your cart items across pages. When you checkout, PHP session data (
$_SESSION["cart"]) is processed to generate an invoice. - Form Validation: PHP validates payment details (e.g., card number format) before processing.
- Sessions: Maintain your cart items across pages. When you checkout, PHP session data (
NTC Website (Nepal)
- Functions: Reusable PHP functions calculate electricity bills based on consumption tiers (e.g.,
calculateBill($units)).
- Functions: Reusable PHP functions calculate electricity bills based on consumption tiers (e.g.,
Exam Tip
- Form Validation: Always validate inputs on the server-side (PHP) even if JavaScript is used client-side. Example:
if (empty($_POST["username"])) { echo "Username is required!"; } - Arrays: Practice traversing and manipulating arrays (e.g.,
foreach,array_push). Examiners often ask for dynamic data handling. - OOP: Focus on:
- Defining classes with properties/methods.
- Creating objects using
new. - Inheritance (
extends) for code reuse.
- JSON: Know how to encode/decode between PHP arrays and JSON strings. API-related questions are common.
- Cookies/Sessions: Understand the difference and when to use each (e.g., sessions for sensitive data like carts).
Pro Tip: For exam questions on form validation, always:
- Check if fields are empty (
empty($_POST["field"])). - Validate email format (
filter_var($email, FILTER_VALIDATE_EMAIL)). - Sanitize inputs (
htmlspecialchars()) to prevent XSS attacks.
In the real world
- Daraz (e-commerce) uses PHP arrays to store product catalogs (multidimensional arrays) and JSON for API responses (e.g., search results).
- eSewa (payment gateway) relies on PHP sessions to track user logins and maintain cart data across pages.
- Nepali banks (e.g., NMB, Global IME) use OOP in PHP to model
Account,Transaction, andCustomerclasses for secure banking operations.
Based on the TU BSc CSIT syllabus for Web Technology (CSC318), unit 8.
Discussion
Loading…