Web Programming Module 3 Important Topics PYQs
Web Programming Module 3 Important Topics PYQs
Topics-PYQs
For more notes visit
https://rtpnotes.vercel.app
Web-Programming-Module-3-Important-Topics-PYQs
Important Topics & PYQs
1. Write a PHP program to check whether the given number is prime or not.
2. List out the sorting functions for Arrays in PHP. Illustrate with suitable examples.
1. sort()
2. rsort()
3. asort()
4. ksort()
3. List six primitive data types used in PHP?
1. Integer
2. Float (or Double)
3. String
4. Boolean
5. Array
6. NULL
4. Give 3 string functions used in PHP associated with removal of whitespaces? How
will they differ each other?
1. trim()
2. ltrim()
3. rtrim()
Summary of Differences:
5. How to use functions in a PHP program with an example.
Steps to Use Functions in PHP
Example of a PHP Program Using Functions
Explanation:
Another Example: Function with Multiple Parameters and No Return Value
6. Distinguish between implode and explode function in PHP with suitable examples.
7. Write a PHP program to check whether the given number is Armstrong or not.
8. Explain any six string handling functions used in PHP with example.
1. strlen() - Get the Length of a String
Example:
2. strtoupper() - Convert a String to Uppercase
Example:
3. strtolower() - Convert a String to Lowercase
Example:
4. substr() - Extract a Substring
Example:
5. strpos() - Find the Position of the First Occurrence of a Substring
Example:
6. trim() - Remove Whitespace from Both Sides of a String
Example:
Summary of Functions:
9. What is the purpose of the implicit arrays $POST and $GET in PHP? Consider that
a web page displays a form containing two text boxes (named num1 and num2),
where the user enters numeric data. Write a PHP script which collects this form data,
finds the sum, difference and the product of the two numbers and then displays the
same with suitable messages. Assume that the script is to be embedded in the web
page specified by the action attribute of the form and that the method used when the
form is submitted is GET.
Purpose of $POST and $GET in PHP:
Example PHP Script Using $GET:
HTML Form (index.html):
PHP Script (calculate.php):
Explanation:
Example:
10. Why is PHP considered to be dynamically typed?
Key Features of PHP’s Dynamic Typing:
11. Develop a PHP program to print the factorial of a number using a function that
accepts number as input and returns the factorial?
12. Why is regular expressions used in PHP? What are the 3 components of a
regular expression? Name any two Pearl compatible functions used with regular
expressions?
Three Components of a Regular Expression
Two Perl-Compatible Functions Used with Regular Expressions in PHP
13. Write a program to
14. Write a PHP program to compute the sum of the positive integers up to 100 using
do while loop.
15. Explain the loops used in PHP with example.
1. for loop
Syntax:
Example:
Explanation:
Output:
2. while loop
Syntax:
Example:
Explanation:
Output:
3. do-while loop
Syntax:
Example:
Explanation:
Output:
4. foreach loop
Syntax:
Example:
Explanation:
Output:
Example with Key-Value Pair (Associative Array):
Output:
16. Write equivalent PHP statements corresponding to the following:
- i. Declare an Associative Array Named "ages"
- ii. Modify the Value Associated with the Key "Megha" to 28
- iii. Sort the Array According to Values Maintaining Key-Value Relationships and Print
- iv. Access the Entry Identified by the Key "Alice"
17. Design a HTML form to input a string and to display whether it is palindrome or
not on form submission using PHP script.
18. Write a PHP script to search for a specific string pattern in a text.
19. Different types arrays with examples in PHP
1. Indexed Arrays
Example:
2. Associative Arrays
Example:
3. Multidimensional Arrays
Example:
<?php
// Function to check if a number is prime
function isPrime($num) {
// A prime number is greater than 1 and divisible only by 1 and itself
if ($num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
// Get the number from user input (via command line or form)
$number = 11; // You can replace this with any number or use user input
Example:
<?php
$array = [4, 2, 8, 1, 5];
sort($array);
print_r($array); // Outputs: [1, 2, 4, 5, 8]
?>
2. rsort()
Example:
<?php
$array = [4, 2, 8, 1, 5];
rsort($array);
print_r($array); // Outputs: [8, 5, 4, 2, 1]
?>
3. asort()
Example:
<?php
$array = ["a" => 4, "b" => 2, "c" => 8, "d" => 1];
asort($array);
print_r($array); // Outputs: ["d" => 1, "b" => 2, "a" => 4, "c" => 8]
?>
4. ksort()
Example:
<?php
$array = ["a" => 4, "b" => 2, "c" => 8, "d" => 1];
ksort($array);
print_r($array); // Outputs: ["a" => 4, "b" => 2, "c" => 8, "d" => 1]
?>
1. Integer
Description: Represents whole numbers (positive or negative) without any decimal points.
Example:
$age = 25; // Integer
3. String
4. Boolean
5. Array
6. NULL
Description: Represents a variable with no value assigned to it. It is used to indicate the
absence of a value.
Example:
1. trim()
Description: Removes whitespaces (or other predefined characters) from the beginning
and end of a string.
Example:
Usage: trim() is used when you want to remove unwanted whitespace or characters
from both ends of the string, such as leading and trailing spaces, tabs, or newline
characters.
Key Difference: It only affects the start and end of the string, not spaces between words.
2. ltrim()
Description: Removes whitespaces (or other predefined characters) from the left
(beginning) of the string.
Example:
$str = " Hello World! ";
$leftTrimmed = ltrim($str);
echo $leftTrimmed; // Output: "Hello World! "
Usage: ltrim() is useful when you want to remove spaces or other unwanted characters
only from the beginning of the string.
Key Difference: It affects only the left side of the string, leaving the right side intact.
3. rtrim()
Description: Removes whitespaces (or other predefined characters) from the right (end)
of the string.
Example:
Usage: rtrim() is used when you want to remove spaces or other unwanted characters
from the end of the string.
Key Difference: It affects only the right side of the string, leaving the left side intact.
Summary of Differences:
1. Define a Function: A function is defined using the function keyword, followed by the
function name, parentheses () , and a block of code enclosed in curly braces {} .
2. Call the Function: Once the function is defined, you can call it in your program by simply
writing its name followed by parentheses.
3. Pass Arguments to Functions (Optional): Functions can accept parameters
(arguments) to perform actions on the data passed to them.
4. Return Values (Optional): Functions can return values using the return keyword. The
return value can be used elsewhere in the program.
<?php
?>
Explanation:
1. Function Definition:
The function greet($name) is defined with one parameter $name .
Inside the function, the return statement creates a greeting message by
concatenating "Hello, " with the value of $name , followed by an exclamation
mark.
2. Function Call:
In the main program, we define a variable $name = "John" .
We then call the greet($name) function, passing the value of $name as an
argument.
3. Display the Output:
The function returns a greeting message, which is stored in the $message variable.
Finally, the echo statement outputs the value of $message , which is "Hello,
John!" .
<?php
?>
Explanation:
The explode(",", $string) function takes a string and splits it at each comma, creating
an array.
implode() : This function joins array elements into a single string, using a specified
delimiter.
Example:
<?php
$array = array("apple", "banana", "orange");
$string = implode(", ", $array);
echo $string; // Output: apple, banana, orange
?>
Explanation:
The implode(", ", $array) function takes an array and joins its elements into a single
string, separated by a comma and space.
Example:
Explanation: The string "Hello, World!" has 13 characters, so strlen() returns 13.
Example:
$string = "hello";
echo strtoupper($string); // Output: HELLO
Example:
$string = "HELLO";
echo strtolower($string); // Output: hello
The substr() function extracts a part of a string starting from a specified position and
optionally up to a specified length.
Example:
Explanation: The function extracts 5 characters starting from position 7 (the "W" in "World").
The output is "World".
The strpos() function finds the position of the first occurrence of a substring in a string. It
returns false if the substring is not found.
Example:
Explanation: The substring "World" starts at position 7 in the string, so strpos() returns 7.
The trim() function removes whitespace (or other specified characters) from both ends of a
string.
Example:
Summary of Functions:
Let's say you have a form with two text boxes ( num1 and num2 ) where the user enters numeric
values. You want to calculate the sum, difference, and product of these two numbers and
display the results.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h2>Simple Calculator</h2>
<form action="calculate.php" method="GET">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required><br><br>
</body>
</html>
PHP Script (calculate.php):
<?php
// Check if the form has been submitted using GET method
if (isset($_GET['num1']) && isset($_GET['num2'])) {
// Retrieve the numbers from the form data
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
// Perform calculations
$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;
Explanation:
It then retrieves the numeric values entered by the user using $_GET['num1'] and
$_GET['num2'] .
The script calculates the sum, difference, and product of the two numbers.
The results are then displayed using echo .
Example:
If the user enters 5 for num1 and 3 for num2 and submits the form, the URL will look like
this:
http://yourdomain.com/calculate.php?num1=5&num2=3
Results:
Sum: 8
Difference: 2
Product: 15
1. No Explicit Type Declaration: In PHP, you don't need to specify the type of a variable
when you declare it. The variable type is automatically inferred based on the value it holds
at runtime.
Example:
$number = 5; // PHP infers that $number is an integer
$text = "Hello, world!"; // PHP infers that $text is a string
$price = 19.99; // PHP infers that $price is a float
2. Changing Types During Execution: A variable's type can change dynamically during
execution. PHP allows a variable to hold a value of any type, and it can change that type
whenever a new value is assigned.
Example:
3. No Need for Type Conversion: PHP automatically converts types when necessary (type
casting). For example, if you try to add an integer to a string, PHP will attempt to convert
the string to a number.
Example:
$a = 10; // Integer
$b = "20"; // String
$sum = $a + $b; // PHP automatically converts $b to an integer,
resulting in $sum = 30
echo $sum; // Outputs 30
4. Type Checking at Runtime: PHP checks the variable's type at the moment the variable is
used, rather than at the start of the program. This allows flexibility in handling different
types, but it can also lead to runtime errors if types don't match the expected operations.
Example:
<?php
// Function to calculate factorial
function calculateFactorial($number) {
// Initialize the factorial to 1
$factorial = 1;
1. Literal Characters: These are the basic characters that the regex will match exactly as
they appear. For example, /abc/ will match the string "abc".
2. Metacharacters: These are special characters that have a specific meaning in regular
expressions. They allow you to define patterns more flexibly. Common metacharacters
include:
. (dot) - Matches any single character except a newline.
3. Quantifiers: These specify how many times a character or group should be matched. For
example:
* - Matches 0 or more occurrences.
? - Matches 0 or 1 occurrence.
PHP provides several functions to work with regular expressions, especially Perl-Compatible
Regular Expressions (PCRE), which are more powerful and flexible. Here are two commonly
used PCRE functions:
1. preg_match() :
This function searches a string for a pattern and returns true if the pattern is found,
and false otherwise.
Example:
if (preg_match("/abc/", "abcdef")) {
echo "Pattern found!";
} else {
echo "Pattern not found.";
}
2. preg_replace() :
This function performs a search and replace operation based on a regular expression
pattern. It searches for a pattern and replaces it with a specified string.
Example:
<?php
// Declare an associative array with items and their prices
$items = array(
"Bread" => 30,
"Butter" => 30,
"Jam" => 35,
"Cheese" => 32
);
// Print the original array using foreach loop
echo "Original Array:\n";
foreach ($items as $key => $value) {
echo "$key => $value\n";
}
<?php
// Initialize variables
$sum = 0;
$i = 1;
1. for loop
2. while loop
3. do-while loop
4. foreach loop (used specifically for arrays)
1. for loop
The for loop is used when you know the number of iterations beforehand. It consists of three
parts:
Syntax:
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration number: $i <br>";
}
?>
Explanation:
Output:
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
2. while loop
The while loop is used when you want to repeat a block of code as long as a condition is true.
It checks the condition before each iteration.
Syntax:
while (condition) {
// Code to be executed
}
Example:
<?php
$i = 1;
while ($i <= 5) {
echo "Iteration number: $i <br>";
$i++; // Increment the counter
}
?>
Explanation:
The loop starts with $i = 1 and continues running as long as $i is less than or equal to
5.
After each iteration, $i is incremented.
Output:
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
3. do-while loop
The do-while loop is similar to the while loop, but it guarantees that the block of code will
run at least once, even if the condition is false initially. It checks the condition after the loop
executes, which means the loop will always run at least once.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
<?php
$i = 1;
do {
echo "Iteration number: $i <br>";
$i++; // Increment the counter
} while ($i <= 5);
?>
Explanation:
The code inside the do block runs first, and then the condition $i <= 5 is checked after
the first execution.
Output:
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
4. foreach loop
The foreach loop is specifically used for iterating over arrays. It simplifies the process of
accessing each element in an array without the need for using a counter.
Syntax:
Example:
<?php
$fruits = ["Apple", "Banana", "Orange", "Grapes"];
Explanation:
$fruits is an array, and the foreach loop will iterate over each element in the array.
Output:
I love Apple
I love Banana
I love Orange
I love Grapes
<?php
$items = ["Bread" => 30, "Butter" => 40, "Jam" => 35];
Output:
Bread costs 30
Butter costs 40
Jam costs 35
<?php
$ages = array(
"Harry" => 21,
"Alice" => 20,
"Megha" => 22,
"Bob" => 19
);
?>
<?php
$ages["Megha"] = 28;
?>
iii. Sort the Array According to Values Maintaining Key-Value Relationships and Print
<?php
asort($ages); // Sort by values while maintaining keys
<?php
echo "Alice's age is: " . $ages["Alice"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Check</title>
</head>
<body>
<h2>Palindrome Checker</h2>
<?php
// PHP Script to check if the string is a palindrome
if (isset($_POST['submit'])) {
// Get the input string from the form
$inputString = $_POST['inputString'];
</body>
</html>
<?php
// Sample text
$textInput = "The quick brown fox jumps over the lazy dog";
// The pattern you want to search for
$searchPattern = "fox";
1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays
1. Indexed Arrays
An indexed array is an array where each element is associated with an index (numeric key).
The index is automatically assigned starting from 0.
Example:
<?php
// Indexed array
$fruits = ["Apple", "Banana", "Cherry"];
// Accessing elements
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana
?>
2. Associative Arrays
An associative array is an array where each element is associated with a custom key (a string
or other type) instead of an automatically assigned index.
Example:
<?php
// Associative array
$person = [
"name" => "John",
"age" => 25,
"city" => "New York"
];
// Accessing elements
echo $person["name"]; // Outputs: John
echo $person["age"]; // Outputs: 25
?>
3. Multidimensional Arrays
A multidimensional array is an array that contains other arrays. It can be thought of as an array
of arrays.
Example:
<?php
// Multidimensional array
$contacts = [
"John" => ["email" => "john@example.com", "phone" => "1234567890"],
"Jane" => ["email" => "jane@example.com", "phone" => "0987654321"]
];
// Accessing elements
echo $contacts["John"]["email"]; // Outputs: john@example.com
echo $contacts["Jane"]["phone"]; // Outputs: 0987654321
?>