Web Programming IIUnit 38 min read
PHP Basics & Syntax: Variables, Control Flow, Functions & Output
Unit 3 of Web Programming II introduces PHP’s core syntax—variables, data types, control structures, functions, and basic I/O—with hands-on examples for dynamic web content generation, validation, and file handling.
TAKEAWAYS:
- PHP is a server-side scripting language embedded in HTML to generate dynamic content.
- Variables in PHP start with
$and support dynamic typing (no declaration needed). - Control structures (
if,for,while) enable logic branching and iteration. - Functions modularize code; PHP supports both built-in and user-defined functions.
- Output is generated via
echo/printor HTML templates; error handling useserror_get_last(). - Real-world use: Khalti’s payment validation, Daraz’s order processing, and Ncell’s user session tracking rely on PHP’s syntax.
1. Introduction to PHP
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language designed for web development. It processes logic on the server, generates dynamic HTML, and interacts with databases. Unlike client-side languages (JavaScript), PHP runs before the page is sent to the browser.
Key Features:
- Embedded in HTML:
<php echo "Hello"; ?> - Cross-platform: Works on Linux, Windows, macOS.
- Database integration: MySQL, PostgreSQL, SQLite.
- Extensible: Supports OOP and procedural programming.
2. PHP Syntax Basics
PHP code is enclosed in <?php ... ?> tags. Below are core syntax elements:
Variables
- Variables start with
$(e.g.,$name). - Case-sensitive:
$Name≠$name. - Dynamic typing: No need to declare types.
flowchart TD
A["$name = 'Alice'"] --> B["$name = 10"] --> C["$name = true"]
C -->|"PHP allows re-assignment"| D["No type errors"]Data Types
PHP supports 8 primary data types:
| Type | Example | Description |
|---|---|---|
| String | "Hello" |
Text in quotes |
| Integer | 42 |
Whole numbers |
| Float | 3.14 |
Decimal numbers |
| Boolean | true/false |
Logical values |
| Array | [$a, $b] |
Ordered/associative lists |
| Object | new DateTime() |
OOP instances |
| Resource | Database handle | System resources (e.g., file handles) |
| NULL | null |
No value |
3. Output in PHP
PHP generates output using:
echo: Displays variables/strings (no semicolon needed).print: Similar toechobut returns1.var_dump(): Debugs variable types/values.
Example: Dynamic HTML Output
<?php
$name = "John";
echo "<h1>Hello, $name!</h1>"; // Output: <h1>Hello, John!</h1>
?>
4. Control Structures
PHP uses if, else, switch, for, while, and foreach for logic.
Conditional Statements
flowchart TD
A["Start"] --> B{"age >= 18?"}
B -->|"Yes"| C["Adult\n(age ≥ 18)"]
B -->|"No"| D["Minor\n(age < 18)"]
C --> E["Can vote"]
D --> F["Cannot vote"]Example: Age Validation
<?php
$age = 20;
if ($age >= 18) {
echo "Eligible to vote.";
} else {
echo "Too young.";
}
?>
Output:
Eligible to vote.
Loops
for: Fixed iterations.while: Runs while condition is true.foreach: Iterates arrays.
Example: Print Numbers 1–5
<?php
for ($i = 1; $i <= 5; $i++) {
echo "$i ";
}
?>
Output:
1 2 3 4 5
5. Functions
Functions encapsulate reusable logic. PHP has built-in functions (e.g., date(), rand()) and user-defined ones.
User-Defined Functions
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Output: Hello, Alice!
?>
Built-in Functions
| Function | Purpose |
|---|---|
date() |
Current date/time |
rand() |
Random number |
strtolower() |
Converts string to lowercase |
file_get_contents() |
Reads file content |
Example: Generate Unique ID
<?php
function generateID() {
return "ID-" . rand(1000, 9999);
}
echo generateID(); // Example: ID-4567
?>
6. Arrays in PHP
Arrays store multiple values in a single variable. Types:
- Indexed: Ordered (e.g.,
$fruits[0] = "Apple"). - Associative: Key-value pairs (e.g.,
$books["title"] = "PHP Guide").
Example: Associative Array (Books)
<?php
$books = [
"title1" => "PHP Basics",
"title2" => "Advanced PHP"
];
foreach ($books as $title) {
echo "$title<br>";
}
?>
Output:
PHP Basics
Advanced PHP
7. File Handling
PHP reads/writes files using fopen(), fread(), fwrite().
Example: Save User Data to File
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$file = fopen("users.txt", "a");
fwrite($file, "$name, $age\n");
fclose($file);
?>
8. Error Handling
PHP logs errors via error_get_last() or ini_set('display_errors', 1).
Example: Catch Errors
<?php
try {
$result = 10 / 0; // Division by zero
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Output:
Error: Division by zero
In the Real World
Khalti’s Payment Validation
- Idea Used: PHP’s
if-elseandPOSTdata handling. - How: When a user submits payment details, Khalti’s backend uses PHP to validate fields (e.g., card number format) before processing the transaction. If invalid, it shows an error like:
if (!preg_match("/^\d{16}$/", $cardNumber)) { echo "Invalid card number!"; }
- Idea Used: PHP’s
Daraz’s Order Processing
- Idea Used: PHP arrays and loops.
- How: Daraz stores order items in an associative array:
The loop calculates the total price dynamically.$order = [ "item1" => ["name" => "Laptop", "price" => 20000], "item2" => ["name" => "Mouse", "price" => 500] ]; $total = array_sum(array_map(fn($item) => $item["price"], $order));
Ncell’s User Session Tracking
- Idea Used: PHP sessions (
session_start()). - How: When you log into Ncell’s app, PHP creates a session ID:
This ID persists across pages, enabling personalized dashboards.session_start(); $_SESSION['user'] = "user123";
- Idea Used: PHP sessions (
Worked Example: Date Difference Calculator
Problem: Calculate the difference between two dates (e.g., 2023-10-01 and 2023-10-15).
Solution:
<?php
$date1 = "2023-10-01";
$date2 = "2023-10-15";
$diff = strtotime($date2) - strtotime($date1);
echo "Difference: " . round($diff / (60 * 60 * 24)) . " days";
?>
Output:
Difference: 14 days
Comparison Table: PHP vs. JavaScript
| Feature | PHP | JavaScript |
|---|---|---|
| Execution | Server-side | Client-side |
| Syntax | <?php ... ?> |
<script> ... </script> |
| Typing | Dynamic | Dynamic (ES6+ supports types) |
| Use Case | Backend logic, databases | Frontend interactivity |
Advantages/Disadvantages
| Advantages | Disadvantages |
|---|---|
| Fast execution (server-side) | Security risks (SQL injection) |
| Easy database integration | Verbose syntax compared to Python |
| Cross-platform support | Requires server (not standalone) |
Exam Tip
- Focus on:
- Variable declaration and data types (e.g.,
$name = "Alice";). - Control structures (
if,for,while) with traces. - Functions: Define and call (e.g.,
function add($a, $b) { return $a + $b; }). - File handling:
fopen(),fwrite()for saving data. - Error handling: Use
try-catchorerror_get_last().
- Variable declaration and data types (e.g.,
- Common Pitfalls:
- Forgetting
$before variables (e.g.,$namevs.name). - Incorrect array syntax (e.g.,
$arr[0]vs.$arr{0}). - Mixing PHP and HTML tags (e.g.,
<?php echo "<h1>"; ?>).
- Forgetting
- Past Exam Patterns:
- 50%: Write a PHP script for a given task (e.g., file handling, validation).
- 30%: Explain syntax (e.g., "How to create a 2D array?").
- 20%: Debug errors (e.g., "Fix this code to display an error message").
Visual Recap:
flowchart TD
A["PHP Script"] --> B["Server Processes\n(Interpreter)"]
B --> C["Generates HTML/CSS\n(Dynamic Content)"]
C --> D["Browser Renders\n(Client-Side)"]
D --> E["Dynamic Web Page"]
C -->|"Also"| F["JSON/XML\n(API Responses)"]Based on the TU BITM syllabus for Web Programming II (IT219), unit 3.
Discussion
Loading…