Web Technology II · Unit 1
PHP Fundamentals and Syntax
Exam-focused notes for PHP Fundamentals and Syntax (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.
PHP Fundamentals and Syntax in short
PHP is a popular language for building dynamic web pages. This chapter explains how PHP runs on a server, how to write its basic syntax, and how it handles variables, types and strings.
What this unit covers
- Server side scripting concepts
- Embedding PHP code in web pages
- PHP comments and documentation
- Variable definition and declaration
- Loosely typed language characteristics
- Data types and type casting operators
- String operations and concatenation
Loosely typed language characteristics
2082 · 10 marks
Why is PHP a loosely typed language? How is the for loop different from the foreach loop? Write a PHP program to demonstrate the use of both loops.[10]
Show solved answerHide answer
PHP: Loosely Typed Language, for vs foreach Loops
Part A: Why is PHP a Loosely Typed Language?
PHP is called a loosely typed (or dynamically typed) language because:
- Variables do not require explicit data type declaration
- The data type of a variable is automatically determined at runtime based on the value assigned to it
- The same variable can hold different types of values at different points in the program
- PHP performs automatic type conversion (known as type juggling) when needed in expressions
Example Illustrating Loose Typing:
<?php
$x = 10; // $x is integer
$x = "Hello"; // $x is now a string (no error)
$x = 3.14; // $x is now a float
// Type juggling example
$result = "5" + 10; // PHP automatically converts "5" to integer
echo $result; // Output: 15
?>
Contrast: In strongly typed languages like Java or C, you must declare
int x = 10;and assigning a string toxlater causes a compile-time error. PHP removes this restriction entirely.
Part B: Difference Between for Loop and foreach Loop
| Feature | for Loop | foreach Loop |
|---|---|---|
| Purpose | Used when the number of iterations is known in advance | Used to iterate over arrays or collections |
| Syntax | Requires initialization, condition, and increment | Requires only the array and a loop variable |
| Index Control | Programmer manually manages the index | Index/key is handled automatically |
| Use Case | Counter-based or numeric repetition tasks | Traversing all elements of an array |
| Risk | Can cause infinite loop if condition is wrong | Always terminates after the last element |
| Key-Value Access | Not directly supported | Supports key => value pair access |
Part C: PHP Program Demonstrating Both Loops
<?php
// -----------------------------------------------
// 1. Demonstrating for loop
// -----------------------------------------------
echo "Using for loop: ";
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . " ";
}
echo " ";
// -----------------------------------------------
// 2. Demonstrating foreach loop (indexed array)
// -----------------------------------------------
echo "Using foreach loop (indexed array): ";
$fruits = array("Apple", "Banana", "Mango", "Orange", "Grapes");
foreach ($fruits as $fruit) {
echo "Fruit: " . $fruit . " ";
}
echo " ";
// -----------------------------------------------
// 3. Demonstrating foreach loop (associative array)
// -----------------------------------------------
echo "Using foreach loop (key => value): ";
$marks = array("Math" => 90, "Science" => 85, "English" => 78);
foreach ($marks as $subject => $score) {
echo $subject . " : " . $score . " ";
}
?>
Expected Output:
Using for loop:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Using foreach loop (indexed array):
Fruit: Apple
Fruit: Banana
Fruit: Mango
Fruit: Orange
Fruit: Grapes
Using foreach loop (key => value):
Math : 90
Science : 85
English : 78
Summary
| Point | Detail |
|---|---|
| Loosely Typed | No type declaration needed; type determined at runtime; type juggling occurs automatically |
| for loop | Best for counter-based iteration where the number of repetitions is known |
| foreach loop | Best for traversing arrays; supports both indexed and associative arrays cleanly |
PHP's loosely typed nature makes development faster and more flexible, while the foreach loop simplifies array traversal by eliminating the need for manual index management.
Server side scripting concepts
2081 · 10 marks
What is server side scripting? How can you define and declare variables in PHP? Write PHP programs to demonstrate concepts of while and do while loops.[10]
Show solved answerHide answer
Server Side Scripting, PHP Variables, and Loops
Part A: Server Side Scripting
Server side scripting is a technique used in web development where scripts are executed on the web server rather than on the client's browser. The server processes the script, generates output (usually HTML), and sends only the final result to the client. The user cannot view the original source code.
How it works:
- The client sends a request to the server (e.g., requesting a
.phpfile) - The web server identifies the script and passes it to the appropriate interpreter (e.g., PHP interpreter)
- The interpreter executes the code, interacts with databases if needed, and produces HTML output
- The server sends this HTML response back to the client's browser
Examples of server side scripting languages: PHP, Python (Django/Flask), ASP.NET, Node.js, JSP
Advantages:
- Dynamic web page generation
- Database interaction is possible
- Source code is hidden from the client
- Supports user authentication, session management, etc.
Part B: Defining and Declaring Variables in PHP
PHP is a loosely typed language, meaning there is no need to explicitly declare the data type of a variable. Variables are declared using the dollar sign ($) followed by the variable name.
Rules for declaring variables:
- Must start with
$followed by the variable name - Variable name must begin with a letter or underscore (not a digit)
- Variable names are case-sensitive (
$Ageand$ageare different) - No data type declaration is required; PHP assigns it automatically
Example:
<?php
$name = "John"; // String variable
$age = 25; // Integer variable
$price = 99.5; // Float variable
$is_active = true; // Boolean variable
echo $name . " ";
echo $age;
?>
Variable Scopes in PHP:
| Scope | Description |
|---|---|
| Local | Declared inside a function; accessible only within that function |
| Global | Declared outside a function; accessible outside (use global keyword inside functions) |
| Static | Retains its value even after the function finishes executing |
Part C: While Loop in PHP
The while loop is an entry-controlled loop. The condition is checked before executing the loop body. If the condition is false initially, the loop body never executes.
Syntax:
while (condition) {
// code to execute
}
Program: Print numbers 1 to 5 using while loop
<?php
$i = 1;
while ($i <= 5) {
echo "Number: " . $i . " ";
$i++;
}
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Part D: Do-While Loop in PHP
The do-while loop is an exit-controlled loop. The loop body is executed at least once, and then the condition is checked. If the condition is true, the loop continues.
Syntax:
do {
// code to execute
} while (condition);
Program: Print numbers 1 to 5 using do-while loop
<?php
$i = 1;
do {
echo "Number: " . $i . " ";
$i++;
} while ($i <= 5);
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Key Difference: While vs Do-While
| Feature | While Loop | Do-While Loop |
|---|---|---|
| Type | Entry-controlled | Exit-controlled |
| Condition check | Before loop body | After loop body |
| Minimum executions | 0 times (if condition is false) | At least 1 time |
| Semicolon after condition | Not required | Required (; after while) |
Conclusion
Server side scripting enables dynamic web content generation on the server. PHP provides simple variable declaration using $ with no type declaration needed. The while loop checks the condition before execution (entry-controlled), while the do-while loop guarantees at least one execution by checking the condition after the loop body (exit-controlled).
Embedding PHP code in web pages
2080 · 10 marks
How can you embed PHP code in web pages? Write a PHP program to illustrate the concepts of continue and break statements.[10]
PHP comments and documentation
2079 · 5 marks
How are comments written in PHP? Write a PHP program that will read your name and roll number and print the values. Label your program with appropriate comments. [5]
String operations and concatenation
2079 · 5 marks
Write a PHP program that will contain a concat string function. The function should have two arguments st1 and st2 of type string and should return st3 which is concatenation of st1 and st2. [5]
0 · 5 marks
Write a PHP program that will read two input strings in variable fname and lname and display concatenation of fname and lname. [5]
Variable definition and declaration
0 · 5 marks
How can you define variable in PHP. Illustrate with example. [5]
Make Unit 1 stick
Practice BIT301 with flashcards & quizzes