CS310 – Open Source Web Application Development (PHP): Midterm Important Subjective (41 Solved Q&As)
Computer Science • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS310 Course Page · CS310 MCQ Pack (53 MCQs)
-
What is PHP? Write any four features/characteristics of PHP.
Topic: PHP Basics & Syntax • 3 marks marks
PHP stands for "PHP: Hypertext Preprocessor". It is a widely used, open source, server-side scripting language that is especially suited for web development and can be embedded into HTML. PHP scripts are executed on the server and the result is returned to the browser as plain HTML. Main features of PHP are: (1) It is free to download and use (open source). (2) It runs on almost all platforms (Windows, Linux, Unix, Mac OS X) and is compatible with almost all servers (Apache, IIS, etc.). (3) It can generate dynamic page content, collect form data, and send and receive cookies. (4) It supports a wide range of databases and is easy to learn. PHP files have the extension ".php".
-
Write the basic syntax of a PHP script. How is PHP code embedded in an HTML page?
Topic: PHP Basics & Syntax • 3 marks marks
A PHP script starts with <?php and ends with ?>. These tags tell the server where the PHP code begins and ends. PHP code can be placed anywhere in an HTML document, and a PHP file normally contains HTML tags along with PHP scripting code. Every PHP statement ends with a semicolon (;). Output is produced with the echo or print statement. Example: <html> <body> <?php echo "Hello World!"; ?> </body> </html>
-
Differentiate between the echo and print statements in PHP.
Topic: PHP Basics & Syntax • 2 marks marks
(1) echo has no return value, while print has a return value of 1, so print can be used in expressions. (2) echo can take multiple parameters (arguments separated by commas), while print can take only one argument. (3) echo is marginally faster than print. Both are language constructs and are used to output data to the screen.
-
What are comments in PHP? Write the syntax for a single-line comment and a multi-line comment in PHP.
Topic: PHP Basics & Syntax • 2 marks marks
Comments are lines in the code that are not executed; they are used to explain the code and make it more readable. In PHP, a single-line comment is written with // (or #), and a multi-line comment is written between /* and */. // This is a single-line comment # This is also a single-line comment /* This is a multi-line comment */
-
What can PHP do? List the main uses/capabilities of PHP.
Topic: PHP Basics & Syntax • 3 marks marks
With PHP we can: (1) Generate dynamic page content. (2) Create, open, read, write and close files on the server. (3) Collect form data sent by the user. (4) Send and receive cookies. (5) Add, delete and modify data in a database. (6) Control user access and encrypt data. PHP is not limited to outputting HTML; it can also output images, PDF files and other content.
-
What is a variable in PHP? Write the rules for naming a PHP variable.
Topic: Variables, Data Types, Constants & Scope • 3 marks marks
In PHP, a variable is a container for storing data/information. A variable starts with the $ sign, followed by the name of the variable. PHP is a loosely typed language, so a variable does not need to be declared before adding a value to it; it is automatically created when a value is assigned to it. Rules for naming a variable: (1) A variable name must start with a letter or the underscore character. (2) A variable name cannot start with a number. (3) A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9 and _). (4) Variable names are case-sensitive, so $age and $AGE are two different variables. $txt = "Hello"; $x = 5;
-
List and briefly explain the data types supported in PHP.
Topic: Variables, Data Types, Constants & Scope • 5 marks marks
PHP supports the following data types: (1) String — a sequence of characters in quotes, e.g. "Hello world!". (2) Integer — a whole number without decimals, e.g. 5985. (3) Float (double) — a number with a decimal point or in exponential form, e.g. 10.365. (4) Boolean — represents two possible states, TRUE or FALSE. (5) Array — stores multiple values in one single variable. (6) Object — an instance of a class, storing data and information about how to process it. (7) NULL — a variable with no value assigned to it. (8) Resource — stores a reference to functions and resources external to PHP (e.g. a database connection).
-
What is variable scope in PHP? Explain local and global scope.
Topic: Variables, Data Types, Constants & Scope • 3 marks marks
Variable scope means the part of the script where a variable can be accessed/used. PHP has three different variable scopes: local, global and static. Global scope: A variable declared outside a function has a GLOBAL scope and can only be accessed outside a function. Local scope: A variable declared within a function has a LOCAL scope and can only be accessed within that function.
-
Explain the static scope in PHP with the help of an example.
Topic: Variables, Data Types, Constants & Scope • 3 marks marks
Normally, when a function completes/finishes executing, all of its local variables are deleted. Sometimes we want a local variable NOT to be deleted, but to remember its value for further use of the function. For this we use the static keyword when the variable is first declared. A static variable is local to the function but retains its previous value when the function is called again. function myTest() { static $x = 0; echo $x; $x++; } myTest(); // outputs 0 myTest(); // outputs 1 myTest(); // outputs 2
-
What is a constant in PHP? How is a constant defined? Differentiate between a constant and a variable.
Topic: Variables, Data Types, Constants & Scope • 5 marks marks
A constant is an identifier (name) for a simple value that cannot change during the execution of the script. A valid constant name starts with a letter or underscore (no $ sign before the name). Constants are automatically global across the entire script. A constant is defined by using the define() function. Differences: (1) A variable name starts with the $ sign, a constant name has no $ sign. (2) A variable's value can be changed during the script; a constant's value cannot be changed or undefined after it is set. (3) Variables are defined by simple assignment (=); constants are defined with the define() function. (4) By convention, constant names are usually written in uppercase. define("GREETING", "Welcome to VU!"); echo GREETING;
-
How can a global variable be accessed inside a function in PHP?
Topic: Variables, Data Types, Constants & Scope • 2 marks marks
A global variable cannot be accessed directly inside a function. It can be accessed in two ways: (1) By using the global keyword before the variable name inside the function, e.g. global $x; (2) By using the $GLOBALS array, in which PHP stores all global variables, e.g. $GLOBALS['x']. function myTest() { global $x; echo $x; }
-
List the different types of operators in PHP with one example of each.
Topic: Operators • 3 marks marks
PHP operators are grouped as follows: (1) Arithmetic operators, e.g. + (addition), - , * , / , % (modulus), ** (exponentiation). (2) Assignment operators, e.g. = , += , -= . (3) Comparison operators, e.g. == , === , != , > , < . (4) Increment/Decrement operators, e.g. ++$x, $x--. (5) Logical operators, e.g. && (and), || (or), ! (not). (6) String operators, e.g. . (concatenation). (7) Array operators, e.g. + (union), == (equality).
-
Differentiate between the == and === comparison operators in PHP.
Topic: Operators • 2 marks marks
The == operator (equal) returns true if the two operands have the same value after type conversion (type juggling), even if their data types are different. The === operator (identical) returns true only if the operands have the same value AND the same data type. For example, 100 == "100" is true, but 100 === "100" is false because one is an integer and the other is a string.
-
Explain the increment and decrement operators in PHP. What is the difference between pre-increment and post-increment?
Topic: Operators • 3 marks marks
The increment operator ++ increases the value of a variable by one, and the decrement operator -- decreases it by one. In pre-increment (++$x), the value is first incremented and then returned/used. In post-increment ($x++), the original value is first returned/used and then incremented. The same rule applies to --$x (pre-decrement) and $x-- (post-decrement). $x = 10; echo ++$x; // 11 (incremented first) $x = 10; echo $x++; // 10 (used first, then becomes 11)
-
Explain the logical operators used in PHP with examples.
Topic: Operators • 2 marks marks
Logical operators are used to combine conditional statements: (1) && or 'and' — true if both operands are true, e.g. ($x > 5 && $x < 20). (2) || or 'or' — true if either of the operands is true, e.g. ($x == 5 || $x == 10). (3) ! (not) — reverses the result; returns true if the operand is not true, e.g. !($x == 5). Another logical operator is 'xor', which is true if either operand is true but not both.
-
Explain the if-elseif-else statement with its syntax and a suitable example.
Topic: Control Structures (if / else / switch) • 5 marks marks
The if-elseif-else statement is used to execute some code if one of the several conditions is true. The conditions are tested in order: the first condition that evaluates to true is executed, and the remaining conditions are skipped. If none of the conditions is true, the else block is executed. Syntax: if (condition1) { code to execute if condition1 is true; } elseif (condition2) { code to execute if condition2 is true; } else { code to execute if all conditions are false; } Example: $marks = 75; if ($marks >= 80) { echo "Grade A"; } elseif ($marks >= 60) { echo "Grade B"; } else { echo "Grade C"; } // Output: Grade B
-
Explain the switch statement in PHP with its syntax. When is it preferred over if-elseif-else?
Topic: Control Structures (if / else / switch) • 3 marks marks
The switch statement is used to perform different actions based on different conditions. It selects one of many blocks of code to be executed, by comparing a single expression/variable against different case values. The break statement stops the execution from falling into the next case, and the default block runs when no case matches. It is preferred over a long if-elseif-else chain when the same variable/expression is to be tested against many different values, because the code becomes simpler and easier to read. switch ($day) { case 1: echo "Monday"; break; case 2: echo "Tuesday"; break; default: echo "Other day"; }
-
Write a PHP program that uses if-else to check whether a number is even or odd.
Topic: Control Structures (if / else / switch) • 5 marks marks
The modulus operator % gives the remainder of a division. If a number divided by 2 gives remainder 0, the number is even; otherwise it is odd. The if statement tests this condition and the else part handles the other case. <?php $num = 7; if ($num % 2 == 0) { echo "$num is Even"; } else { echo "$num is Odd"; } ?> // Output: 7 is Odd
-
Differentiate between the while loop and the do-while loop in PHP.
Topic: Loops • 3 marks marks
(1) In a while loop the condition is checked first and then the body of the loop is executed; in a do-while loop the body is executed first and then the condition is checked. (2) A while loop may execute zero times if the condition is false at the start, whereas a do-while loop is guaranteed to execute at least one time. (3) The while loop is an entry-controlled loop, while the do-while loop is an exit-controlled loop.
-
Explain the for loop in PHP with its syntax and an example. When should a for loop be used?
Topic: Loops • 3 marks marks
The for loop is used when the exact number of iterations (times the loop should run) is known in advance. It has three parts separated by semicolons: initialization (executed once, at the beginning), condition (evaluated before every iteration), and increment/decrement (executed at the end of every iteration). Syntax: for (init; condition; increment) { code to be executed; } Example: for ($i = 0; $i < 5; $i++) { echo "i = $i <br>"; } // Loop body executes 5 times
-
What is the foreach loop in PHP? Write its syntax with an example.
Topic: Loops • 3 marks marks
The foreach loop works only on arrays and is used to loop through each key/value pair in an array. For every loop iteration, the value of the current array element is assigned to a variable and the array pointer moves to the next element, so no counter or condition is needed. Syntax: foreach ($array as $value) { code to be executed; } Or: foreach ($array as $key => $value) { ... } Example: $colors = array("red", "green", "blue"); foreach ($colors as $value) { echo "$value <br>"; }
-
Write a PHP program using a loop to print the multiplication table of 5 (from 5 x 1 to 5 x 10).
Topic: Loops • 5 marks marks
A for loop is suitable because the number of iterations (10) is known in advance. In each iteration the loop counter is multiplied by 5 and the result is printed. <?php $num = 5; for ($i = 1; $i <= 10; $i++) { echo "$num x $i = " . ($num * $i) . "<br>"; } ?> // Output: 5 x 1 = 5, 5 x 2 = 10, ... , 5 x 10 = 50
-
What is a function in PHP? Write the syntax for creating a user-defined function with an example.
Topic: Functions • 5 marks marks
A function is a block of statements that can be used repeatedly in a program. A function is not executed automatically when a page loads; it is executed only when it is called. PHP has more than 1000 built-in functions, and we can also create our own (user-defined) functions. A function declaration starts with the keyword function, followed by the function name and parentheses; function names are not case-sensitive but cannot start with a number. function writeMsg() { echo "Hello world!"; } writeMsg(); // calling the function // Output: Hello world!
-
How are arguments passed to a function in PHP? Also explain default argument values.
Topic: Functions • 3 marks marks
Information can be passed to functions through arguments, which behave like local variables inside the function. Arguments are specified after the function name, inside the parentheses, separated by commas. By default, arguments are passed by value, so changing the argument's value inside the function does not change its value outside the function. A default value can also be set for an argument; if the function is called without that argument, the default value is used. function familyName($fname, $year = "unknown") { echo "$fname born in $year <br>"; } familyName("Ali", "1995"); familyName("Sara"); // uses the default value
-
How does a function return a value in PHP? Explain with an example.
Topic: Functions • 2 marks marks
A function can return a value to the code that called it by using the return statement. As soon as return is executed, the function stops executing and the value is sent back to the calling code, where it can be stored in a variable or used directly. function sum($x, $y) { return $x + $y; } echo sum(5, 10); // Output: 15
-
What is an array in PHP? Explain the types of arrays in PHP.
Topic: Arrays & String Functions • 5 marks marks
An array is a special variable that can hold more than one value at a time under a single name, and the values can be accessed by referring to an index number or a key name. Arrays are created with the array() function. PHP has three types of arrays: (1) Indexed arrays — arrays with numeric indexes, e.g. $cars = array("Volvo", "BMW", "Toyota"); where "Volvo" has index 0. (2) Associative arrays — arrays with named keys, e.g. $age = array("Ali" => "35", "Sara" => "37"); (3) Multidimensional arrays — arrays containing one or more arrays inside them.
-
Write a short note on any five commonly used string functions in PHP.
Topic: Arrays & String Functions • 3 marks marks
(1) strlen() — returns the length of a string, e.g. strlen("Hello") returns 5. (2) str_word_count() — counts the number of words in a string. (3) strrev() — reverses a string, e.g. strrev("Hello") gives "olleH". (4) strpos() — searches for a specific text within a string and returns the position of the first occurrence. (5) str_replace() — replaces some characters/words with other characters/words in a string, e.g. str_replace("world", "Dolly", "Hello world!") gives "Hello Dolly!".
-
Write a PHP program to create an indexed array of fruits and display all its elements using a loop.
Topic: Arrays & String Functions • 3 marks marks
An indexed array is created with the array() function, and its elements get numeric indexes starting from 0. The foreach loop is the easiest way to display all elements of an array one by one. <?php $fruits = array("Apple", "Banana", "Mango", "Orange"); foreach ($fruits as $fruit) { echo "$fruit <br>"; } ?>
-
Differentiate between the GET and POST methods of sending form data in PHP.
Topic: Forms, GET & POST and Superglobals • 3 marks marks
(1) In GET, the form data is appended to the URL and is visible to everyone; in POST, the data is sent in the body of the HTTP request and is not visible in the URL. (2) GET has limits on the amount of information that can be sent (about 2000 characters); POST has no limits. (3) GET requests can be bookmarked and should never be used for sensitive data like passwords; POST is more secure and is used for sensitive/large data. (4) GET is used for retrieving data, while POST is used for sending/modifying data.
-
What are superglobal variables in PHP? Name any four. How is form data collected using $_GET and $_POST?
Topic: Forms, GET & POST and Superglobals • 3 marks marks
Superglobals are built-in variables that are always available in all scopes throughout a script, no matter where they are used. Examples are $GLOBALS, $_SERVER, $_REQUEST, $_GET, $_POST, $_FILES, $_COOKIE and $_SESSION. When a form is submitted, its field values are collected using the superglobal matching the form's method: if the form uses method="get", values are collected with $_GET['fieldname']; if it uses method="post", values are collected with $_POST['fieldname']. <form method="post" action="welcome.php"> Name: <input type="text" name="name"> </form> // In welcome.php: <?php echo $_POST["name"]; ?>
-
What is the include statement in PHP? Write its syntax and explain its use.
Topic: Include Statement, date() Function, Cookies & Sessions • 3 marks marks
The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement, before the server executes that file. It is very useful when the same HTML, PHP or text is repeated on multiple pages of a website, such as a header, footer or menu: instead of repeating the code on every page, it is kept in one file and included wherever needed, so updating one file updates all pages. Syntax: include 'filename'; Example: <?php include 'footer.php'; ?>
-
Explain the date() function in PHP. What do the format characters d, m, Y and l represent?
Topic: Include Statement, date() Function, Cookies & Sessions • 3 marks marks
The date() function formats a local date and time and returns the formatted date string. Its syntax is date(format, timestamp), where the format parameter is required and specifies how the date/time is to be formatted, and the timestamp is optional. Important format characters are: d — represents the day of the month (01 to 31); m — represents a month (01 to 12); Y — represents a year in four digits (e.g. 2026); l (lowercase L) — represents the day of the week in full text (e.g. Monday). echo "Today is " . date("Y/m/d"); // e.g. Today is 2026/01/15
-
What is a cookie in PHP? How is a cookie created and retrieved?
Topic: Include Statement, date() Function, Cookies & Sessions • 3 marks marks
A cookie is a small file that the server embeds on the user's computer; it is often used to identify a user. Each time the same computer requests a page, it also sends the cookie with the request. A cookie is created with the setcookie() function, which must appear BEFORE the <html> tag. Its main parameters are the cookie name, value, and expiry time. The value of a cookie is retrieved using the $_COOKIE superglobal. A cookie is deleted by setting its expiry time to a time in the past. setcookie("user", "Ali Ahmad", time() + 3600, "/"); // Retrieve it on another page: echo $_COOKIE["user"];
-
What is a session in PHP? Explain how a session is started, how session variables are set, and how a session is destroyed.
Topic: Include Statement, date() Function, Cookies & Sessions • 5 marks marks
A session is a way to store information (variables) about a single user across multiple pages, e.g. a username or login status. Unlike a cookie, the information is not stored on the user's computer but on the server. A session is started with the session_start() function, which must be the very first thing in the document, before any HTML tags. Session variables are set with the PHP global variable $_SESSION. To completely destroy the session, session_unset() removes all session variables and session_destroy() destroys the session. session_start(); $_SESSION["username"] = "Ali"; echo $_SESSION["username"]; // To end the session: session_unset(); session_destroy();
-
Differentiate between cookies and sessions in PHP.
Topic: Include Statement, date() Function, Cookies & Sessions • 3 marks marks
(1) Cookies store data on the user's (client) computer, while session data is stored on the server. (2) Sessions are more secure than cookies because the data is not kept on the user's machine. (3) A cookie can store only a small amount of data and has a size limit; a session can store much larger data. (4) A cookie remains available even after the browser is closed (until its expiry time), while a session normally ends when the user closes the browser or the session is destroyed. (5) Cookies are accessed with $_COOKIE and sessions with $_SESSION after calling session_start().
-
Write down a complete PHP code to display your name.
Topic: PHP Basics & Syntax • 3 marks marks
A complete PHP code that displays a name using the echo statement is: <?php echo "Ali Ahmed"; ?> The code is written between the opening tag <?php and the closing tag ?>, and the echo statement displays the given name on the web page.
-
Write the name of each type of loop in PHP.
Topic: Loops • 2 marks marks
There are four types of loops in PHP. Their names are as follows: 1. for Loop 2. while Loop 3. do-while Loop 4. foreach Loop
-
What will be the output of the following code? for($i = 1; $i<=3; $i++) echo $i*2 . "<br>";
Topic: Loops • 3 marks marks
The for loop will execute three times; each time it will multiply the value of $i with 2 and display the result. The output will be as follows: 2 4 6
-
Write the code of for loop in PHP which will calculate the sum of all numbers from 1 to 20 and then display its value on the screen.
Topic: Loops • 5 marks marks
<?php $sum = 0; for ($i = 1; $i <= 20; $i++) { $sum = $sum + $i; } echo "Sum of numbers from 1 to 20 is: " . $sum; ?> The for loop runs from 1 to 20 and keeps adding each value of $i into the variable $sum. After the loop ends, the total is displayed on the screen. Output: Sum of numbers from 1 to 20 is: 210
-
What will be the output of the following code? <?php echo strrev("Pakistan"); ?>
Topic: Arrays & String Functions • 2 marks marks
The strrev() function reverses a string, so the output of this code will be: natsikaP
-
Write PHP code using string functions that will replace word "and" with "AND" in the given below paragraph. After replacing and with AND display the paragraph. (5 marks) Paragraph: The territory that now constitutes Pakistan was previously home to several ancient cultures, including the Mehrgarh of the Neolithic and the Bronze Age Indus Valley Civilization, and was later home to kingdoms ruled by people of different faiths and cultures.
Topic: Arrays & String Functions
The str_replace() string function is used to replace all occurrences of a word in a string: <?php $paragraph = "The territory that now constitutes Pakistan was previously home to several ancient cultures, including the Mehrgarh of the Neolithic and the Bronze Age Indus Valley Civilization, and was later home to kingdoms ruled by people of different faiths and cultures."; echo str_replace("and", "AND", $paragraph); ?> After replacing "and" with "AND", the paragraph displayed will be: The territory that now constitutes Pakistan was previously home to several ancient cultures, including the Mehrgarh of the Neolithic AND the Bronze Age Indus Valley Civilization, AND was later home to kingdoms ruled by people of different faiths AND cultures.