Current Affairs updated daily
KalviGavaniKalviGavani

Introduction to PHP Exercise Solutions | KalviGavani

Complete Samacheer Kalvi Class 12 Computer Applications Chapter 4 exercise solutions covering PHP basics, syntax, variables, data types, operators, embedding PHP in HTML, and server-side scripting with detailed explanations.

Updated 13 June 202623 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

Chapter 4 — Introduction to Hypertext Pre-Processor (PHP): Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise question on your own first — use your Samacheer Kalvi textbook and class notes. 2. Compare your answers with the solutions below only after you have written your own. 3. Read the explanations for MCQs and True/False items — understanding why an answer is correct is more important than the answer itself. 4. Practise the short and detailed answers by writing them in your own words; do not memorise verbatim. 5. Use the Exam Checklist at the end for a quick pre-exam revision round.


Key Concepts (Quick Recap)

  • PHP stands for Hypertext Pre-Processor (recursive acronym); it is a server-side scripting language for web development.
  • PHP code is embedded in HTML using <?php ... ?> tags; the server processes PHP and sends plain HTML to the browser.
  • PHP files have the extension .php; they must be served through a web server (Apache, Nginx) with PHP installed.
  • Variables in PHP start with a $ symbol (e.g., $name, $age); they are loosely typed — no need to declare the type.
  • Data types in PHP: Integer, Float (Double), String, Boolean, Array, Object, NULL, Resource.
  • Operators: Arithmetic (+, -, *, /, %), Assignment (=, +=, -=), Comparison (==, !=, >, <), Logical (&&, ||, !).
  • String operators: Concatenation (.) and concatenation assignment (.=).
  • echo and print are used to output data; echo has no return value and can take multiple arguments; print returns 1 and takes one argument.
  • Comments: Single-line (// or #) and multi-line (/ ... /).
  • Case sensitivity: Variable names are case-sensitive ($Name and $name are different); function names and keywords are not case-sensitive.
  • Constants are defined using define() or const keyword; they cannot be changed once defined.
  • PHP supports both procedural and object-oriented programming paradigms.

I. Choose the Best Answer (MCQs)

1. PHP stands for: (a) Personal Home Page (b) Hypertext Pre-Processor (c) Hyperlink Processing Language (d) Home Text Processor

Answer(b) Hypertext Pre-Processor PHP originally stood for "Personal Home Page" but was later changed to the recursive acronym "PHP: Hypertext Pre-Processor." The current official expansion is Hypertext Pre-Processor.

2. Which symbol is used to declare a variable in PHP? (a) # (b) & (c) $ (d) @

Answer(c) $ All PHP variables must start with a dollar sign ($). Example: $name = "Arun";. Variable names are case-sensitive and must begin with a letter or underscore.

3. Which of the following is the correct PHP opening tag? (a) <% ... %> (b) <script language="php"> ... </script> (c) <?php ... ?> (d) <? ... ?>

Answer(c) <?php ... ?> The standard and most compatible PHP tag is <?php ... ?>. While short tags <? ... ?> may work if short_open_tag is enabled, <?php ... ?> is the recommended and portable form.

4. Which PHP function is used to define a constant? (a) const() (b) define() (c) constant() (d) setconst()

Answer(b) define() The define() function creates a constant that cannot be changed during script execution. Example: define("PI", 3.14);. You can also use the const keyword: const PI = 3.14;

5. What is the output of the following PHP code?
<?php
$x = 10;
$y = "10";
echo ($x == $y) ? "Same" : "Different";
?>
Answer

(a) Different (b) Same (c) Error (d) 0

Answer(b) Same The == operator checks for value equality only (loose comparison). Since $x (integer 10) and $y (string "10") have the same value, the comparison returns true. The === operator would check both value and type.

6. Which data type in PHP represents a whole number? (a) Float (b) String (c) Boolean (d) Integer

Answer(d) Integer Integer is a whole number without a decimal point. Example: $age = 20;. Float (also called Double) represents numbers with decimals. String represents text. Boolean represents true/false.

7. What will be the output of echo "Hello" . " " . "World";? (a) HelloWorld (b) Hello World (c) Hello. .World (d) Error

Answer(b) Hello World The . operator in PHP is the string concatenation operator. It joins strings together. "Hello" . " " . "World" concatenates three strings to produce "Hello World".

8. Which of the following is NOT a valid PHP variable name? (a) $name (b) $_age (c) $1st_place (d) $studentName

Answer(c) $1st_place PHP variable names must start with a letter or underscore, not a number. $1st_place starts with a digit after the dollar sign, making it invalid. $name, $_age, and $studentName are all valid.

9. In PHP, which keyword is used to display output? (a) display (b) write (c) echo (d) output

Answer(c) echo echo is a language construct (not a function) used to output one or more strings. It is the most commonly used output command in PHP. print is another option but can only take one argument.

10. PHP is a: (a) Client-side scripting language (b) Server-side scripting language (c) Database language (d) Markup language

Answer(b) Server-side scripting language PHP code is executed on the web server, not in the browser. The server processes PHP code and sends the resulting HTML output to the client. This is different from client-side languages like JavaScript.

II. Fill in the Blanks

1. PHP stands for Hypertext Pre-Processor. 2. All PHP variables must start with the $ symbol. 3. The standard PHP opening tag is <?php and the closing tag is ?>. 4. The string concatenation operator in PHP is the . (dot) operator. 5. The define() function is used to create a constant in PHP. 6. The data type that represents true or false values is Boolean. 7. PHP variables are loosely typed — you do not need to declare the data type. 8. The === operator checks both value and type. 9. Single-line comments in PHP can be written using // or #. 10. The file extension for PHP scripts is .php.


III. True or False

1. PHP is a client-side scripting language.
AnswerFalse — PHP is a server-side scripting language. The PHP code is executed on the server, and only the HTML output is sent to the browser.
2. PHP variable names are case-sensitive.
AnswerTrue — $name and $Name are treated as two different variables in PHP. Variable names are case-sensitive.
3. The echo statement can accept multiple arguments separated by commas.
AnswerTrue — echo can accept multiple arguments: echo "Hello", " ", "World"; is valid. print can only accept one argument.
4. $123abc is a valid PHP variable name.
AnswerFalse — PHP variable names cannot start with a number after the $ sign. Valid names must start with a letter or underscore. $abc123 would be valid.
5. The == operator checks both value and data type.
AnswerFalse — == checks only value equality (loose comparison). The === operator checks both value and data type (strict comparison).
6. PHP can be embedded directly within HTML.
AnswerTrue — PHP code is embedded in HTML using <?php ... ?> tags. The server processes the PHP portions and outputs the resulting HTML.
7. A constant in PHP can be changed after it is defined.
AnswerFalse — By definition, a constant cannot be changed once it is defined using define() or const. That is what distinguishes constants from variables.
8. The % operator in PHP returns the remainder of division.
AnswerTrue — The % (modulus) operator returns the remainder. Example: 10 % 3 returns 1.
9. PHP requires you to declare variable types before use.
AnswerFalse — PHP is loosely typed. Variables are automatically cast to the appropriate type based on the value assigned. No type declaration is needed.
10. The print statement returns a value.
AnswerTrue — print returns 1 (integer) when executed, while echo returns nothing. This is why echo is slightly faster.

IV. Match the Following

Set A

Column AColumn B
1. Integer(d) Whole number without decimal
2. Float(a) Number with decimal point
3. String(e) Sequence of characters
4. Boolean(c) True or False value
5. Array(b) Collection of multiple values

Set B

Column AColumn B
1. ==(e) Value comparison only
2. ===(a) Value and type comparison
3. !=(b) Not equal
4. .(d) String concatenation
5. %(c) Modulus (remainder)

V. Short Answer Questions

1. What is PHP? Explain its features.
Answer

PHP (Hypertext Pre-Processor) is an open-source, server-side scripting language designed primarily for web development. It is embedded within HTML and processed on the server to generate dynamic web pages.

Key Features:

  • Server-side execution — PHP code runs on the server, not in the browser
  • Open source — free to use and distribute
  • Cross-platform — runs on Windows, Linux, macOS
  • Embedded in HTML — PHP code can be mixed with HTML using <?php ... ?> tags
  • Database support — works with MySQL, PostgreSQL, SQLite, Oracle, and more
  • Loosely typed — no need to declare variable types
  • Large community — extensive documentation and community support
  • Fast — efficient execution on web servers

Simple PHP example:

<?php
  echo "Hello, World!";
?>
2. How do you embed PHP code in HTML? Give an example.
Answer

PHP code is embedded in HTML using the <?php ... ?> tags. The server processes only the PHP portions and sends the resulting HTML to the browser.

<!DOCTYPE html>
<html>
<head>
    <title>PHP in HTML</title>
</head>
<body>
    <h1>Welcome to PHP</h1>
    <?php
        $name = "Arun";
        echo "<p>Hello, " . $name . "!</p>";
    ?>
    <p>This is static HTML content.</p>
    <?php
        $age = 20;
        echo "<p>Age: " . $age . "</p>";
    ?>
</body>
</html>

Output in browser:

Welcome to PHP Hello, Arun! This is static HTML content. Age: 20

The browser receives only HTML — the PHP code is processed and replaced on the server before the page is sent.

3. Explain PHP variables with rules for naming.
Answer

PHP variables are containers for storing data values. They are declared with the $ symbol followed by the variable name.

Rules for naming PHP variables: 1. Must start with $ followed by a letter or underscore 2. Cannot start with a number after $ 3. Can contain letters, numbers, and underscores 4. Are case-sensitive ($name and $Name are different) 5. Cannot contain spaces 6. Should not use PHP reserved keywords

<?php
  // Valid variable names
  $name = "Arun";
  $_age = 20;
  $student_name = "Bharathi";
  $marks2 = 85;

  // Invalid variable names
  // $1st_place = "Gold";    // Cannot start with number
  // $student name = "Arun"; // Cannot contain space
?>

PHP is loosely typed — the same variable can hold different data types:

<?php
  $x = 10;       // $x is Integer
  $x = 3.14;     // $x is now Float
  $x = "Hello";  // $x is now String
?>
4. Explain PHP data types with examples.
Answer

PHP supports 8 data types, divided into 3 categories:

Scalar Types (simple values):

1. Integer — whole numbers without decimals

   $age = 20;
   $count = -5;

2. Float (Double) — numbers with decimal points

   $price = 99.50;
   $pi = 3.14159;

3. String — sequence of characters in quotes

   $name = "Arun";
   $msg = 'Hello World';

4. Boolean — logical value, true or false

   $is_student = true;
   $has_passed = false;

Compound Types (collections):

5. Array — ordered collection of values

   $colors = array("Red", "Green", "Blue");
   $scores = [85, 92, 78];

6. Object — instance of a class

   class Student {
       public $name;
   }
   $s = new Student();

Special Types:

7. NULL — variable with no value

   $result = NULL;

8. Resource — reference to external resource (e.g., database connection)

   $conn = mysqli_connect("localhost", "root", "");
5. Differentiate between echo and print in PHP.
Answer
Featureechoprint
TypeLanguage constructLanguage construct
Return valueNone (void)Returns 1
ArgumentsMultiple (comma-separated)Single argument only
SpeedSlightly fasterSlightly slower
ParenthesesOptionalOptional
Usage in expressionsCannot be usedCan be used (returns value)
<?php
  // echo with multiple arguments
  echo "Hello", " ", "World";  // Output: Hello World

  // print with single argument
  print "Hello World";          // Output: Hello World

  // print returns a value (can be used in expressions)
  $result = print "Hi";         // Output: Hi, $result = 1
?>
6. What are operators in PHP? Explain arithmetic and comparison operators.
Answer

Arithmetic Operators:

OperatorNameExampleResult
+Addition$a + $bSum of $a and $b
-Subtraction$a - $bDifference
*Multiplication$a * $bProduct
/Division$a / $bQuotient
%Modulus$a % $bRemainder
**Exponentiation$a ** $b$a raised to power $b
<?php
  $a = 15;
  $b = 4;
  echo $a + $b;  // 19 (Addition)
  echo $a - $b;  // 11 (Subtraction)
  echo $a * $b;  // 60 (Multiplication)
  echo $a / $b;  // 3.75 (Division)
  echo $a % $b;  // 3 (Modulus - remainder)
?>

Comparison Operators:

OperatorNameExampleResult
==Equal$a == $bTrue if values are equal
===Identical$a === $bTrue if value AND type are equal
!=Not equal$a != $bTrue if values are not equal
<>Not equal$a <> $bSame as !=
!==Not identical$a !== $bTrue if value OR type differ
>Greater than$a > $bTrue if $a is greater
<Less than$a < $bTrue if $a is less
>=Greater than or equal$a >= $bTrue if $a is greater or equal
<=Less than or equal$a <= $bTrue if $a is less or equal
<?php
  $x = 10;
  $y = "10";
  var_dump($x == $y);   // bool(true)  — same value
  var_dump($x === $y);  // bool(false) — different types
?>

VI. Detailed Answer Questions

1. Explain the working of PHP as a server-side scripting language with a diagram.
Answer

PHP is a server-side scripting language — the code is executed on the web server, not on the client (browser). Here is how it works:

Step-by-step working: 1. The user types a URL or clicks a link that requests a .php file 2. The browser sends an HTTP request to the web server 3. The web server (Apache/Nginx) recognises the .php extension 4. The server passes the PHP file to the PHP interpreter (PHP engine) 5. The PHP interpreter processes the PHP code between <?php ?> tags 6. PHP may connect to a database (MySQL) to fetch or store data 7. The PHP interpreter generates HTML output from the PHP code 8. The server sends the pure HTML response back to the browser 9. The browser renders the HTML page for the user

Request-Response Flow:

Client (Browser) Server | | |--- HTTP Request (.php) ------>| | |---> PHP Engine | | |-- Process PHP code | | |-- Connect to MySQL (optional) | | |-- Generate HTML | |<--- HTML Output |<-- HTTP Response (HTML) ------| | | Browser displays HTML

Key points:

  • The client never sees the PHP source code — only the HTML output
  • PHP can interact with databases, files, and external services on the server
  • Dynamic content (user-specific, database-driven) is generated before the page reaches the browser
  • The same PHP file can produce different HTML for different users

Example:

<?php
  // File: welcome.php
  $hour = date("H");
  if ($hour < "12") {
      echo "Good Morning!";
  } elseif ($hour < "18") {
      echo "Good Afternoon!";
  } else {
      echo "Good Evening!";
  }
?>

When a user visits welcome.php, the server determines the current hour and sends an appropriate greeting. The browser only sees "Good Morning!" or "Good Afternoon!" — never the PHP code.


2. Explain PHP variables, constants, and their differences in detail.
Answer

PHP Variables:

Variables are containers for storing data. In PHP:

  • Declared with $ followed by the variable name
  • No type declaration needed (loosely typed)
  • Value can be changed during execution
  • Case-sensitive
<?php
  $name = "Arun";        // String
  $age = 20;             // Integer
  $height = 5.8;         // Float
  $is_student = true;   // Boolean

  // Variable values can be changed
  $age = 21;             // $age is now 21

  // Variable interpolation in double quotes
  echo "My name is $name and I am $age years old.";
?>

Variable Scope:

  • Local — declared inside a function, accessible only within that function
  • Global — declared outside functions, accessible anywhere (use global keyword inside functions)
  • Static — persists its value between function calls (use static keyword)
<?php
  $x = 10;  // Global scope

  function test() {
      global $x;  // Access global variable inside function
      echo $x;
  }
?>

PHP Constants:

Constants are identifiers for fixed values that cannot be changed during execution.

  • Defined using define() function or const keyword
  • Do not start with $
  • Automatically global (accessible anywhere in the script)
  • Cannot be redefined or undefined once set
<?php
  // Using define()
  define("SITE_NAME", "KalviGavani");
  define("PI", 3.14159);

  // Using const keyword
  const MAX_STUDENTS = 40;
  const VERSION = "2.0";

  echo SITE_NAME;    // Output: KalviGavani
  echo PI;           // Output: 3.14159
  echo MAX_STUDENTS; // Output: 40

  // Constants cannot be changed
  // PI = 3.14;      // ERROR! Cannot redefine constant
?>

Differences between Variables and Constants:

FeatureVariableConstant
Declaration$name = value;define("NAME", value); or const NAME = value;
$ prefixRequiredNot used
Value changeCan be changedCannot be changed
ScopeFollows scope rulesAutomatically global
Case-sensitiveYesBy default yes (with define)
Data typesAll typesScalar types and arrays (const)
ReassignmentAllowedNot allowed

3. Explain PHP operators in detail with examples.
Answer

PHP operators are symbols that perform operations on variables and values.

1. Arithmetic Operators:
<?php
  $a = 15;
  $b = 4;
  echo $a + $b;   // 19  (Addition)
  echo $a - $b;   // 11  (Subtraction)
  echo $a * $b;   // 60  (Multiplication)
  echo $a / $b;   // 3.75 (Division)
  echo $a % $b;   // 3   (Modulus - remainder)
  echo $a ** $b;  // 50625 (Exponentiation: 15^4)
?>
2. Assignment Operators:
<?php
  $x = 10;      // Assign
  $x += 5;      // $x = $x + 5  → 15
  $x -= 3;      // $x = $x - 3  → 12
  $x *= 2;      // $x = $x * 2  → 24
  $x /= 4;      // $x = $x / 4  → 6
  $x %= 4;      // $x = $x % 4  → 2
  $x .= "abc";  // $x = $x . "abc" → "2abc" (string concatenation)
?>
3. Comparison Operators:
<?php
  $a = 10;
  $b = "10";

  var_dump($a == $b);   // true  (same value)
  var_dump($a === $b);  // false (different type: int vs string)
  var_dump($a != $b);   // false (same value)
  var_dump($a !== $b);  // true  (different type)
  var_dump($a > 5);     // true
  var_dump($a < 5);     // false
  var_dump($a >= 10);   // true
  var_dump($a <= 9);    // false
?>
4. Logical Operators:
<?php
  $x = true;
  $y = false;

  var_dump($x && $y);   // false (AND — both must be true)
  var_dump($x || $y);   // true  (OR — at least one true)
  var_dump(!$x);        // false (NOT — reverses the value)

  // Alternative syntax
  var_dump($x and $y);  // false (AND — lower precedence)
  var_dump($x or $y);   // true  (OR — lower precedence)
  var_dump($x xor $y);  // true  (XOR — one true, not both)
?>
5. String Operators:
<?php
  $a = "Hello";
  $b = " World";

  // Concatenation (.)
  echo $a . $b;       // "Hello World"

  // Concatenation assignment (.=)
  $a .= $b;           // $a is now "Hello World"
  echo $a;            // "Hello World"
?>
6. Increment/Decrement Operators:
<?php
  $x = 5;

  echo ++$x;  // 6 (Pre-increment: increment then use)
  echo $x++;  // 6 (Post-increment: use then increment)
  echo $x;    // 7

  echo --$x;  // 6 (Pre-decrement: decrement then use)
  echo $x--;  // 6 (Post-decrement: use then decrement)
  echo $x;    // 5
?>
Answer

Operator Precedence (high to low): 1. ++, -- (increment/decrement) 2. *, /, % (multiplication, division, modulus) 3. +, - (addition, subtraction) 4. <, <=, >, >= (comparison) 5. ==, !=, ===, !== (equality) 6. && (logical AND)

8. =, +=, .= (assignment)

7. `` (logical OR)

4. Explain how to embed PHP in HTML with multiple examples.
Answer

PHP can be embedded in HTML in several ways. The server processes the PHP portions and outputs the resulting HTML to the browser.

Example 1: Simple PHP output in HTML

<!DOCTYPE html>
<html>
<head>
    <title>PHP Example</title>
</head>
<body>
    <h1>Welcome</h1>
    <?php
        echo "<p>Today is " . date("d-m-Y") . "</p>";
    ?>
</body>
</html>

Example 2: Using PHP variables in HTML

<!DOCTYPE html>
<html>
<head>
    <title>Student Details</title>
</head>
<body>
    <?php
        $student_name = "Arun";
        $roll_no = 101;
        $marks = 85;
    ?>
    <h1>Student Report</h1>
    <p>Name: <?php echo $student_name; ?></p>
    <p>Roll No: <?php echo $roll_no; ?></p>
    <p>Marks: <?php echo $marks; ?></p>
</body>
</html>

Example 3: PHP conditional logic in HTML

<!DOCTYPE html>
<html>
<head>
    <title>Result</title>
</head>
<body>
    <h1>Exam Result</h1>
    <?php
        $marks = 75;
        if ($marks >= 35) {
            echo "<p style='color:green;'>Pass — Marks: $marks</p>";
        } else {
            echo "<p style='color:red;'>Fail — Marks: $marks</p>";
        }
    ?>
</body>
</html>

Example 4: PHP loop in HTML

<!DOCTYPE html>
<html>
<head>
    <title>Number Table</title>
</head>
<body>
    <h2>Number Table of 5</h2>
    <table border="1">
        <?php
            for ($i = 1; $i <= 10; $i++) {
                echo "<tr><td>5 x $i</td><td>" . (5 * $i) . "</td></tr>";
            }
        ?>
    </table>
</body>
</html>

Example 5: Shorthand PHP tags in HTML

<p>Name: <?= $student_name ?></p>
<!-- <?= ... ?> is shorthand for <?php echo ... ?> -->

Important points about embedding PHP in HTML:

  • The file must have a .php extension (not .html)
  • PHP code must be enclosed in <?php ... ?> tags
  • The server must have PHP installed and configured
  • The browser receives only HTML — PHP code is never visible to the user
  • Multiple PHP blocks can be used in a single file
  • Variables declared in one PHP block are accessible in subsequent blocks

5. Explain PHP comments and the difference between single-line and multi-line comments with examples.
Answer

Comments are non-executable lines in code that explain what the code does. They are ignored by the PHP interpreter.

Single-line Comments:

Used for short explanations. There are two syntaxes:

<?php
  // This is a single-line comment using double slash
  $name = "Arun";  // Comment after code

  # This is a single-line comment using hash
  $age = 20;       # Comment after code
?>

Both // and # make everything after them on the same line a comment. The // style is more commonly used and recommended.

Multi-line Comments:

Used for longer explanations or commenting out multiple lines of code.

<?php
  /*
   * This is a multi-line comment.
   * It can span multiple lines.
   * Useful for detailed explanations.
   */
  $name = "Arun";
  $age = 20;

  /* Multi-line comment can also be used
     to temporarily disable code blocks */
  /*
  $test = "This code won't run";
  echo $test;
  */
?>

When to use comments:

TypeBest ForSyntax
Single-line (//)Brief notes, inline explanations// comment
Single-line (#)Shell-style comments# comment
Multi-line (/ /)Detailed explanations, disabling code blocks/ comment /

Best practices: 1. Use comments to explain why the code does something, not what it does 2. Keep comments concise and relevant 3. Update comments when you change code 4. Use multi-line comments for function/class documentation 5. Avoid over-commenting obvious code

<?php
  // Good comment: explains why
  $discount = 0.10;  // 10% discount for premium members

  // Unnecessary comment: states the obvious
  $total = $price + $tax;  // adds price and tax
?>

Common Mistakes

1. Forgetting the $ before variable names — PHP variables must start with $. Writing name = "Arun" instead of $name = "Arun" causes an error.

2. Confusing == and === — == compares values only (10 == "10" is true); === compares both value and type (10 === "10" is false).

3. Using = instead of == in conditions — if ($x = 5) assigns 5 to $x and is always true. Use if ($x == 5) for comparison.

4. Forgetting the semicolon — Every PHP statement must end with a semicolon. echo "Hello" without ; causes a parse error.

5. Mixing up echo and print differences — echo can take multiple arguments and returns nothing; print takes one argument and returns 1.

6. Using single quotes for variable interpolation — '$name' prints the literal string $name; "$name" prints the variable's value.

7. Confusing server-side and client-side execution — PHP runs on the server. JavaScript runs in the browser. PHP code cannot interact with the DOM directly.


Exam Checklist

  • [ ] Can define PHP and explain its role as a server-side scripting language
  • [ ] Know how to embed PHP in HTML using <?php ... ?> tags
  • [ ] Can declare and use PHP variables following naming rules
  • [ ] Understand all 8 PHP data types with examples
  • [ ] Can use arithmetic, assignment, comparison, logical, and string operators
  • [ ] Know the difference between echo and print
  • [ ] Understand == vs === (loose vs strict comparison)
  • [ ] Can define and use constants with define() and const
  • [ ] Know how to write single-line and multi-line comments
  • [ ] Can explain the request-response flow of PHP on a web server

Frequently Asked Questions

PHP (Hypertext Pre-Processor) is a server-side scripting language designed for web development. It is embedded in HTML and executed on the server to generate dynamic web pages.