1 Php Fundamentals And Syntax

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.

PHP Fundamentals and Syntax: notes

Server side scripting concepts

A server side script runs on the web server, not in the browser. The browser sends a request, the server runs the script, and only the output (usually HTML) goes back to the browser. The user never sees the PHP code.

Working of a PHP request:

  • The browser asks for a page such as index.php.
  • The web server (Apache or Nginx) hands the file to the PHP engine.
  • PHP runs the code, talks to the database if needed, and produces HTML.
  • The server sends that HTML to the browser.

Server side scripting helps to build pages that change with each user, read databases, handle forms, keep login sessions and protect business logic.

Server sideClient side
Runs on the web serverRuns in the browser
PHP, ASP.NET, Python, Node.jsJavaScript, HTML, CSS
Can access database and filesCannot directly access the server database
Code is hidden from the userCode is visible to the user

Embedding PHP code in web pages

PHP code is placed inside the tags <?php and ?>. Anything outside these tags is sent to the browser as plain HTML. The file must be saved with the .php extension.

<html>
<body>
  <h1>Welcome</h1>
  <?php
    $name = "Sita";
    echo "Hello, " . $name;
  ?>
  <p>Today is <?= date("d M Y") ?></p>
</body>
</html>
  • <?php ... ?> is the standard tag and always works.
  • <?= expr ?> is a short way to echo a value.
  • Each statement ends with a semicolon.
  • echo and print send output to the page. echo is slightly faster and can take many values.
  • A file that has only PHP code can leave out the closing ?> tag.

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 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 to x later causes a compile-time error. PHP removes this restriction entirely.


Part B: Difference Between for Loop and foreach Loop

Featurefor Loopforeach Loop
PurposeUsed when the number of iterations is known in advanceUsed to iterate over arrays or collections
SyntaxRequires initialization, condition, and incrementRequires only the array and a loop variable
Index ControlProgrammer manually manages the indexIndex/key is handled automatically
Use CaseCounter-based or numeric repetition tasksTraversing all elements of an array
RiskCan cause infinite loop if condition is wrongAlways terminates after the last element
Key-Value AccessNot directly supportedSupports 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

PointDetail
Loosely TypedNo type declaration needed; type determined at runtime; type juggling occurs automatically
for loopBest for counter-based iteration where the number of repetitions is known
foreach loopBest 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.

Open this answer on its own page →

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 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:

  1. The client sends a request to the server (e.g., requesting a .php file)
  2. The web server identifies the script and passes it to the appropriate interpreter (e.g., PHP interpreter)
  3. The interpreter executes the code, interacts with databases if needed, and produces HTML output
  4. 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 ($Age and $age are 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:

ScopeDescription
LocalDeclared inside a function; accessible only within that function
GlobalDeclared outside a function; accessible outside (use global keyword inside functions)
StaticRetains 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

FeatureWhile LoopDo-While Loop
TypeEntry-controlledExit-controlled
Condition checkBefore loop bodyAfter loop body
Minimum executions0 times (if condition is false)At least 1 time
Semicolon after conditionNot requiredRequired (; 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).

Open this answer on its own page →

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 (Hypertext Preprocessor) is a server-side scripting language. PHP code is embedded directly within HTML documents using special delimiters (tags). The web server processes the PHP code and sends only the resulting HTML output to the browser. This is the most portable and universally supported...

Open this answer on its own page →

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]

PHP accepts three forms of comment, inherited from the languages it grew out of. Two are single line and one spans several lines, and none of them are sent to the browser: the parser strips them before any output is produced. Form Syntax Extent --------- C++ style // text From the marker to the e...

Open this answer on its own page →

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]

Part Description ------------------- function concatString($st1, $st2) Defines a function with two string arguments st1 and st2 $st3 = $st1 . $st2 Uses the . (dot) operator to concatenate the two strings and stores in $st3 return

Open this answer on its own page →

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]

PHP joins strings with the dot operator, so $fname . " " . $lname gives the full name with a single space between the two parts. The two values are typed into an HTML form and read on the server from the

Open this answer on its own page →

Variable definition and declaration

0 · 5 marks

How can you define variable in PHP. Illustrate with example. [5]

A variable in PHP is a named storage location that holds a value. PHP variables are loosely typed, meaning you do not need to declare the data type explicitly -- the type is determined automatically based on the assigned value. --- 1. A variable must start with a dollar sign (

Open this answer on its own page →