Mod 3 Complete
Mod 3 Complete
Mod 3 Complete
1. Server-Side Scripting: PHP is executed on the server, meaning it can generate HTML
that is sent to the client's browser. The user never sees the PHP code itself, only the
output.
2. Dynamic Content Creation: PHP can generate dynamic content based on user input,
such as form submissions, or database queries. For example, it can be used to generate
customized pages for each visitor.
3. Database Integration: PHP is commonly used in combination with MySQL (or other
databases) to create dynamic websites that retrieve and store information. It supports
many database systems including MySQL, PostgreSQL, and SQLite.
4. Object-Oriented Programming (OOP): PHP supports object-oriented programming,
allowing developers to structure code more effectively using classes and objects.
5. Fast and Efficient: PHP is designed for speed and can handle thousands of requests
per second with minimal memory usage. It’s also widely used for Content Management
Systems (CMS) like WordPress.
Basic Example:
<?php
?>
// This is a comment
$x += 10; // Increment $x by 1
<?php
?>
BASIC SYNTAX
Semicolons – $x += 10;
The $ symbol in php we must place a $ infront of all variables this is required to make the phn
parser faster as it instantly knows whenever it comes across a variable.
<php
$mycounter = 1;
$mystring = “hello”
$myarray = array(“one”)
?>
VARIABLES
● A variable in PHP is a special container that you can define, which then “holds” a value,
such as a number, string, object, array, or a Boolean.
● With variables, you can create templates for operations, such as adding two numbers,
without worrying about the specific values the variables represent.
● Values are given to the variables when the script is run, possibly through user input,
through a database query, or from the result of another action earlier in the script.
In PHP, a variable consists of a name of your choosing, preceded by a dollar sign ($). Variable
names can include letters, numbers, and the underscore character (_), but they cannot include
spaces. Names must begin with a letter or an underscore.
Eg $a $a_longish_variable_name
$_24563
$sleepyZZZZ
● A semicolon (;), also known as the instruction terminator, is used to end a PHP
statement.
GLOBAL VARIABLES
For example, if you have scriptA.php that holds a variable called $name with a value of joe, and
you want to create scriptB.php that also uses a $name variable, you can assign to that second
$name variable a value of jane without affecting the variable in scriptA.php. The value of the
$name variable is local to each script, and the assigned values are independent of each other.
the $name variable as global within a script or function. If the $name variable is defined as a
global variable in both scriptA.php and scriptB.php, and these scripts are connected to each
other (that is, one script calls the other or includes the other), there will be just one value for the
now-shared $name variable.
SUPERGLOBAL VARIABLES
PHP has several predefined variables called superglobals. These variables are always present,
and their values are available to all your scripts.
$_GET contains any variables provided to a script through the GET method.
$_POST contains any variables provided to a script through the POST method.
$_COOKIE contains any variables provided to a script through a cookie.
$_FILES contains any variables provided to a script through file uploads.
$_SERVER contains information such as headers, file paths, and script locations.
$_ENV contains any variables provided to a script as part of the server environment.
$_REQUEST contains any variables provided to a script via GET, POST, or COOKIE input
mechanisms.
$_SESSION contains any variables that are currently registered in a session
DATA TYPES
● Explicit type declaration is not needed in php
● The gettype() method used to find the type of given data
SIMPLE PHP PPROGRAM
1. <DOCTYPE HTML>
2.
3. <!-- fig.19.1; first.php – >
4. <! Simple php program. -- >
5. <html>
6. <?php
7. $name = “paul”;//decalaration and initialization
8. ?>
9. <head>
10. <body>
11. <h1><?php (“welcome to php ,$name!”): ?></h1>
12. </body>
13. </html>
3.2 Converting between Data Types, Operators and Expressions -Flow Controlfunctions
Type juggling is the feature of PHP where the variables are automatically cast to best fit data
type in the circumstances while manipulating with mathematical operators.
Type juggling converts automatically to the upper level data type that supports for the
calculation. Following is the example that converts string into integer while adding to the integer.
OUTPUT:
The following output will be generated from the above PHP code.
[insert_php]
$theory=45;
$practical=”15 is the number obtained”;
$sum=$theory+$practical; echo “The Total Number Obtained is ” .$sum;
[/insert_php]
OPERATERS
PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values.
In the above example, + is the binary + operator, 10 and 20 are operands and $num is a
variable.
Flow control in PHP refers to the mechanisms that determine the order in which statements are executed
or evaluated based on specific conditions or iterations. PHP provides several constructs for flow control,
such as conditionals, loops, and decision-making statements.
1. Conditional Statements
Conditional statements execute code based on whether a condition evaluates to true or false.
a. if Statement
Syntax:
php
Copy code
if (condition) {
// Code to execute if condition is true
}
Example:
php
Copy code
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
b. if-else Statement
Syntax:
php
Copy code
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
php
Copy code
$marks = 40;
if ($marks >= 50) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}
c. if-elseif-else Statement
Syntax:
php
Copy code
if (condition1) {
// Code for condition1
} elseif (condition2) {
// Code for condition2
} else {
// Code if no conditions are true
}
Example:
php
Copy code
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} else {
echo "Grade: C";
}
d. switch Statement
Syntax:
php
Copy code
switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Example:
php
Copy code
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the workweek!";
break;
case "Friday":
echo "Almost the weekend!";
break;
default:
echo "It's just another day.";
}
2. Looping Statements
a. while Loop
Syntax:
php
Copy code
while (condition) {
// Code to execute
}
Example:
php
Copy code
$count = 1;
while ($count <= 5) {
echo "Count: $count\n";
$count++;
}
b. do-while Loop
Syntax:
php
Copy code
do {
// Code to execute
} while (condition);
Example:
php
Copy code
$count = 1;
do {
echo "Count: $count\n";
$count++;
} while ($count <= 5);
c. for Loop
Syntax:
php
Copy code
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
php
Copy code
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i\n";
}
d. foreach Loop
Syntax:
php
Copy code
foreach ($array as $value) {
// Code to execute
}
Example:
php
Copy code
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit\n";
}
3. Jump Statements
a. break
Example:
php
Copy code
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo "Number: $i\n";
}
b. continue
Example:
php
Copy code
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo "Number: $i\n";
}
4. Ternary Operator
Syntax:
php
Copy code
(condition) ? value_if_true : value_if_false;
Example:
php
Copy code
$age = 20;
$message = ($age >= 18) ? "Adult" : "Minor";
echo $message;
5. Null Coalescing Operator
Syntax:
php
Copy code
$result = $var1 ?? $var2;
Example:
php
Copy code
$username = $_GET['username'] ?? 'Guest';
echo "Hello, $username";
Functions in PHP
A function is a block of code designed to perform a specific task. Once defined, a function can be reused
multiple times, promoting modular programming.
function functionName(parameters) {
// Code to execute
return value; // Optional
}
b. Calling a Function
functionName(arguments);
PHParrays and arrays in C are quite different in terms of their structure, behavior, and flexibility.
2. Size:
○ PHPArrays:Thesize of a PHP array is dynamic. You can add or remove elements as needed.
○ CArrays:Thesize of a C array is fixed once declared, and the size needs to be known at
compile-time.
3. Indexing:
○ PHPArrays:PHParrays can be indexed numerically or associatively (using strings as keys).
○ CArrays:Carrays are numerically indexed starting from 0.
4. MemoryManagement:
○ PHPArrays:PHPmanagesthe memory dynamically and automatically resizes the array when
elements are added or removed.
○ CArrays:InC,the programmer must manage memory manually. If dynamic behavior is needed,
C requires explicit use of dynamic memory allocation functions (e.g., malloc or calloc).
PHPprovides different ways to create arrays. Below are some common methods:
1. Indexed (Numerical) Array: An array where elements are automatically assigned an index
starting from 0.
$fruits = array("Apple", "Banana", "Orange");
// or using short array syntax: $fruits = ["Apple", "Banana", "Orange"];
2. Associative Array: An array where elements are associated with keys (which can be strings
or numbers).
$age = array("Peter" => 35, "John" => 30, "Jane" => 28);
// or using short array syntax: $age = ["Peter" => 35, "John" => 30, "Jane" => 28];
3. Multidimensional Array: An array that contains arrays as its elements, useful for
representing complex data.
$products = array(
array("Laptop", 1000, 15),
array("Smartphone", 500, 30),
array("Tablet", 300, 20) );
4. Empty Array: Create an empty array and then add elements later.
$colors = array();
// Empty array $colors[] = "Red"; // Add elements later
PHPArray Functions provides numerous functions to handle arrays. Here are four commonly
used functions:
1. array_merge(): This function merges the elements of one or more arrays into a single array.
Output: Array ( [a] => red [b] => green [c] => blue [d] => yellow )
2. array_push(): This function adds one or more elements to the end of an array. $stack =
array("apple", "banana");
3. array_keys(): This function returns all the keys (numeric or string) of an array. php
$age = array("Peter" => 35, "John" => 30, "Jane" => 28);
$keys = array_keys($age);
print_r($keys);
Output: Array ( [0] => Peter [1] => John [2] => Jane )
3.5 Working with Strings-String processing with Regular expression, Pattern Matching
● PHP can process text easily and efficiently, enabling straightforward searching,
substitution, extraction, and concatenation of strings.
● Text manipulation is usually done with regular expressions—a series of characters that
serve as pattern-matching templates (or search criteria) in strings, text files, and
databases.
● Function preg_match uses regular expressions to search a string for a specified
pattern using Perl-compatible regular expressions (PCRE). Figure 19.9 demonstrates
regular expressions.
SEARCHING FOR EXPRESSIONS
1. Line 15 assigns the string "Now is the time" to variable $search.
2. The condition in line 19 calls function preg_match to search for the literal characters
"Now" inside variable $search.
3. If the pattern is found, preg_match returns the length of the matched string—which
evaluates to true in a boolean context—and line 20 prints a message indicating that the
pattern was found.
4. We use single quotes ('') inside the string in the print statement to emphasize the
search pattern.
5. Anything enclosed in single quotes is not interpolated, unless the single quotes are
nested in a double-quoted string literal, as in line 16.
6. For example, '$name' in a print statement would output $name, not variable $name’s
value.
7. Function preg_match takes two arguments—a regular-expression pattern to search for
and the string to search.
8. The regular expression must be enclosed in delimiters—typically a forward slash (/) is
placed at the beginning and end of the regular-expression pattern.
9. By default, preg_match performs case-sensitive pattern matches.
10. To perform case-insensitive pattern matches, you simply place the letter i after the
regular-expression pattern’s closing delimiter, as in "/\b([a-zA-Z]*ow)\b/i" (line
31).
REPRESENTING PATTERNS
Quantifier Table:
FINGING MATCHES
● The optional third argument is an array that stores matches to the regular expression.
Parenthetical Sub-Expressions:
Using preg_replace:
● Lines 38–45 demonstrate using a while loop and the preg_replace function to find
all words in a string starting with the letter t.
CHARACTER CLASSES
○ The \b in the pattern specifies word boundaries, ensuring the match is a whole
word.
6. Case-Insensitive Matching:
1. Quantifier +:
○ The function preg_replace is used to remove the matched string from the
original string.
5. Arguments of preg_replace:
○ The word matched by the regular expression is replaced with an empty string.
○ The modified string is assigned back to $search.
○ This enables matching and printing of any other words starting with the specified
character (e.g., t) in the string.
3.6 Form Processing and Business Logic
UNIVERSTIY QUESTIONS
// Example usage:
$number = 29; // You can change this number to test other numbers
if (isPrime($number)) {
echo $number . " is a prime number.";
} else {
echo $number . " is not a prime number.";
}
?>
When a web page containing embedded PHP is requested by a client browser, the PHP script is
executed on the server side before the response is sent to the client. Here's the sequence:
1. Client sends a request: The browser sends an HTTP request for the PHP file to the web
server.
2. Server processes the request: The web server identifies that the requested file has a
.php extension.
3. PHP script execution:
○ The web server passes the PHP file to the PHP interpreter.
○ The PHP interpreter processes the PHP code inside the file and executes any
server-side logic (e.g., database queries, calculations).
○ Any output from the PHP script (e.g., HTML, JSON, etc.) is generated.
4. Response sent to the client: The server sends back the processed output (e.g., HTML)
to the client browser. Importantly, the browser only receives the result of the PHP
execution, not the PHP code itself.
2. Two Modes of Operation of the PHP Processor
a. Scripting Mode
Example:
<html>
<body>
<h1>Welcome</h1>
<?php
echo "Today is " . date("Y-m-d"); // Dynamically outputs the
current date
?>
</body>
</html>
●
● The PHP interpreter processes the PHP tags (<?php ... ?>) and generates the
corresponding HTML output to send to the client.
● Used for building websites that require dynamic content like user authentication, form
handling, and database interactions.
● PHP can also run scripts from the command line, independent of a web server.
● Useful for automation tasks, running scheduled scripts (cron jobs), or standalone
command-line applications.
Example:
php script.php
● In CLI mode, there’s no involvement of HTML or HTTP; it’s purely server-side and runs
without needing a browser.
5. Why is PHP considered to be dynamically typed? Distinguish between implode and explode
function in PHP with suitable examples.
No explicit type declaration: Variables in PHP do not need to have their data type explicitly
declared when they are created. PHP automatically determines the type of a variable based on
the value assigned to it.
php
Copy code
$x = 10; // $x is an integer
$y = "Hello"; // $y is a string
$z = true; // $z is a boolean
Type can change during runtime: The type of a variable can change based on the value
reassigned to it.
php
Copy code
$x = 10; // Initially an integer
$x = "Now a string"; // Now the type is a string
Type juggling: PHP performs automatic type conversions when needed, which is known as
"type juggling."
php
Copy code
$a = "5";
$b = 10;
$c = $a + $b; // PHP converts $a to an integer; $c is 15
This flexibility makes PHP dynamically typed but also prone to errors in larger systems due to
the lack of strict type enforcement.
Purpos Combines elements of an array into a Splits a string into an array based on a
e single string. delimiter.
Usage Used to create a string from an array Used to parse a string into parts.
(e.g., CSV).
3. Examples
implode() Example
php
Copy code
$array = ["apple", "banana", "cherry"];
$string = implode(", ", $array); // Combines array elements with ", "
echo $string;
// Output: apple, banana, cherry
explode() Example
php
Copy code
$string = "apple, banana, cherry";
$array = explode(", ", $string); // Splits the string at ", "
print_r($array);
// Output: Array ( [0] => apple [1] => banana [2] => cherry )
PHP Program:
<?php
// Step 1: Create an Associative Array to store names and roll numbers
of 10 students
$students = array(
"101" => "Alice",
"102" => "Bob",
"103" => "Charlie",
"104" => "David",
"105" => "Eve",
"106" => "Frank",
"107" => "Grace",
"108" => "Hannah",
"109" => "Ivy",
"110" => "Jack"
);
// Step 2: Display the original array using foreach loop
echo "Original Array:\n";
foreach ($students as $rollNo => $name) {
echo "Roll No: $rollNo, Name: $name\n";
}
echo "\n";
Explanation of Code:
1. Creating the Associative Array:
○ The $students array stores roll numbers as keys and student names as values.
2. Using foreach loop:
○ The foreach loop iterates through the array to print the Roll No and Name.
3. Sorting Operations:
○ asort(): Sorts the array by values in ascending order while maintaining
key-value associations.
○ arsort(): Sorts the array by values in descending order while preserving keys.
○ ksort(): Sorts the array by keys in ascending order.
4. Displaying Results:
○ The sorted arrays are displayed after each sorting operation to illustrate the
changes.
Sample Output:
yaml
Copy code
Original Array:
Roll No: 101, Name: Alice
Roll No: 102, Name: Bob
Roll No: 103, Name: Charlie
Roll No: 104, Name: David
Roll No: 105, Name: Eve
Roll No: 106, Name: Frank
Roll No: 107, Name: Grace
Roll No: 108, Name: Hannah
Roll No: 109, Name: Ivy
Roll No: 110, Name: Jack
8.. Design an HTML page which enters a given number, write a PHP program to display a
message indicating, whether the number is odd or even, when clicking on the submit button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Odd or Even Checker</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f3f4f6;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background: #ffffff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
width: 300px;
text-align: center;
}
input[type="number"] {
width: 90%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 15px;
font-size: 16px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h2>Odd or Even Checker</h2>
<!-- HTML Form -->
<form method="post" action="">
<label for="number">Enter a Number:</label><br>
<input type="number" id="number" name="number"
required><br>
<button type="submit">Check</button>
</form>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the entered number
$number = intval($_POST['number']); // Convert input to an
integer
HTML Part:
1. Form Elements:
○ An <input> element of type="number" is used to allow only numeric values.
○ The method="post" ensures that the data is sent securely to the server.
○ A submit button allows the user to process the input.
2. Styling:
○ The HTML is styled using CSS for a clean layout, centering the form, and adding
visual appeal.
PHP Part:
Output Example:
Case 1: Input = 7
Case 2: Input = 10
9. Write a PHP program to compute the sum of the positive integers up to 100 using do while.
<?php
// Initialize variables
$sum = 0; // To store the cumulative sum
$number = 1; // Starting number
1. Initialization:
○ $sum is initialized to 0 to store the total sum.
○ $number is initialized to 1 as the starting point.
2. do-while Loop:
○ The do block ensures the loop executes at least once.
○ Inside the block:
■ $sum += $number: Adds the current number to the cumulative sum.
■ $number++: Increments the current number by 1.
○ The condition while ($number <= 100) ensures the loop continues until
$number exceeds 100.
3. Result:
○ After the loop completes, the variable $sum contains the sum of integers from 1
to 100.
4. Output:
○ The echo statement displays the calculated sum.
Expected Output:
The sum of positive integers from 1 to 100 is: 5050
10. Write a PHP program to check whether the given number is Armstrong
or not.
PHP Code:
php
Copy code
<?php
// Input: The number to check
$number = 153; // Change this to test with other numbers
Loops in PHP
1. for Loop
Syntax:
php
Copy code
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
php
Copy code
<?php
// Print numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
?>
Output:
javascript
Copy code
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2. while Loop
The while loop is used when the number of iterations is not known in
advance, and the loop continues until a specified condition evaluates
to false.
Syntax:
php
Copy code
while (condition) {
// Code to be executed
}
Example:
php
Copy code
<?php
// Print numbers from 1 to 5
$i = 1;
while ($i <= 5) {
echo "Number: $i<br>";
$i++;
}
?>
Output:
javascript
Copy code
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. do-while Loop
The do-while loop is similar to the while loop but ensures the block
of code is executed at least once, regardless of the condition.
Syntax:
php
Copy code
do {
// Code to be executed
} while (condition);
Example:
php
Copy code
<?php
// Print numbers from 1 to 5
$i = 1;
do {
echo "Number: $i<br>";
$i++;
} while ($i <= 5);
?>
Output:
javascript
Copy code
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
4. foreach Loop
Syntax:
php
Copy code
foreach ($array as $value) {
// Code to be executed
}
Example:
php
Copy code
<?php
// Define an array
$colors = ["Red", "Green", "Blue"];
less
Copy code
Color: Red
Color: Green
Color: Blue
11. List out the sorting functions for Arrays in PHP. Illustrate with
suitable examples.
Examples:
Output:
css
Copy code
Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )
Output:
css
Copy code
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 )
Output:
css
Copy code
Array ( [a] => 1 [b] => 3 [c] => 4 )
Output:
css
Copy code
Array ( [c] => 4 [b] => 3 [a] => 1 )
Output:
Output:
12. 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.
● $_GET: This is a superglobal array that retrieves form data sent using
the HTTP GET method. Data is appended to the URL as query parameters,
making it visible in the browser's address bar.
● $_POST: This is a superglobal array that retrieves form data sent using
the HTTP POST method. Data is sent in the HTTP request body, making it
more secure for sensitive data.
1. How to use the $_GET array to retrieve numeric inputs from a form.
2. Calculating the sum, difference, and product of the entered numbers.
3. Displaying the results with suitable messages.
// Display results
echo "<h2>Results:</h2>";
echo "<p>The sum of $num1 and $num2 is: $sum</p>";
echo "<p>The difference between $num1 and $num2 is: $difference</p>";
echo "<p>The product of $num1 and $num2 is: $product</p>";
} else {
echo "<p>Please enter valid numbers in the form.</p>";
}
?>
How It Works:
1. Form Submission:
The form uses the GET method, so the data is appended to the URL in the
format:
Copy code
arithmetic_operations.php?num1=value1&num2=value2
○
2. PHP Script:
○ The $_GET array retrieves the num1 and num2 values from the query
string.
○ The script converts the inputs to integers and calculates the sum,
difference, and product.
○ Results are displayed dynamically.
Output
python
Copy code
Results:
The sum of 5 and 3 is: 8
The difference between 5 and 3 is: 2
The product of 5 and 3 is: 15
If the user submits the form without entering data (or if accessed directly),
the script displays:
css
Copy code
Please enter valid numbers in the form.
PHP has six primary scalar (primitive) data types, used to represent simple
values.
1. int (Integer):
○ Represents whole numbers (e.g., 10, -5, 0).
Example:
php
Copy code
$age = 25;
○
2. float (Floating-point):
○ Represents decimal numbers or numbers with a fractional part
(e.g., 3.14, -0.9).
Example:
php
Copy code
$price = 99.99;
○
3. string:
○ Represents a sequence of characters (e.g., "Hello", "123").
Example:
php
Copy code
$name = "John Doe";
○
4. bool (Boolean):
○ Represents a value of true or false.
Example:
php
Copy code
$isLoggedIn = true;
○
5. null:
○ Represents a variable with no value or explicitly set to NULL.
Example:
php
Copy code
$value = null;
○
6. resource:
○ Represents a reference to an external resource, such as a database
connection or file handle.
○ Example:
php
Copy code
$file = fopen("example.txt", "r");
PHP provides several functions to manipulate and remove whitespaces from strings. Below are
three commonly used functions for whitespace removal:
1. trim()
Purpose: Removes whitespace (or other characters) from both the beginning and the end of a
string.
Syntax:
php
Copy code
trim($string, $character_mask);
Example:
php
Copy code
<?php
$string = " Hello World! ";
$result = trim($string);
echo $result; // Output: "Hello World!"
?>
Explanation:
Purpose: Removes whitespace (or other characters) from the beginning (left side) of the string
only.
Syntax:
php
Copy code
ltrim($string, $character_mask);
Example:
php
Copy code
<?php
$string = " Hello World! ";
$result = ltrim($string);
echo $result; // Output: "Hello World! "
?>
Explanation:
● Removes whitespace only from the start (left side) of the string.
3. rtrim()
Purpose: Removes whitespace (or other characters) from the end (right side) of the string only.
Syntax:
php
Copy code
rtrim($string, $character_mask);
● $character_mask: (optional) A list of characters to be removed from the right side. By
default, it removes spaces, tabs, and newlines.
Example:
php
Copy code
<?php
$string = " Hello World! ";
$result = rtrim($string);
echo $result; // Output: " Hello World!"
?>
15. Develop a PHP program to print the factorial of a number using a function that accepts
number as input and returns the factorial?
Factorial Function:
The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n.
For example:
● 5! = 5 * 4 * 3 * 2 * 1 = 120
● 0! = 1 by definition.
Steps:
PHP Program:
php
Copy code
<?php
// Function to calculate the factorial
function factorial($num) {
// Initialize the result variable
$result = 1;
// Input number (you can replace this with user input in a form)
$number = 5; // Example number
1. factorial() function:
○ The function factorial() accepts a parameter $num.
○ It checks if the number is negative or zero. If negative, it returns an error
message, as factorial is not defined for negative numbers.
○ If the number is zero, the function returns 1 (as 0! = 1).
○ For positive numbers, a for loop is used to multiply the result iteratively from 1 to
the given number ($num).
2. $number: The number for which the factorial is calculated (you can replace this with
user input through a form if required).
3. Output: The program prints the calculated factorial.
Example Output:
csharp
Copy code
The factorial of 5 is: 120
csharp
Copy code
The factorial of 0 is: 1
csharp
Copy code
Factorial is not defined for negative numbers.
16. 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?
Regular expressions (regex) are used in PHP for pattern matching and
searching within strings. They allow for sophisticated text
processing, enabling tasks such as:
1. Literal Characters:
These are the actual characters that the regular expression will
search for in the string. For example, the regex /apple/ will
search for the exact sequence apple.
○ Example: /hello/ looks for the string hello.
2. Metacharacters:
These are special characters that control how the regex operates.
They modify the behavior of literal characters or define specific
patterns.
○ Examples of metacharacters include:
■ . (dot): Matches any single character except newline.
■ \d: Matches any digit (equivalent to [0-9]).
■ ^: Anchors the pattern to the start of the string.
■ $: Anchors the pattern to the end of the string.
3. Quantifiers:
Quantifiers specify how many times an element in the regex should
appear. They allow the expression to match multiple occurrences
of a pattern.
○ Examples of quantifiers include:
■ *: Matches zero or more occurrences of the preceding
element.
■ +: Matches one or more occurrences of the preceding
element.
■ {n,m}: Matches between n and m occurrences of the
preceding element.
1. preg_match():
○ Purpose: Performs a regular expression match.
○ Syntax: preg_match($pattern, $subject, &$matches, $flags,
$offset)
○ Description: Searches a string for a pattern and returns
whether the pattern was found.
Example:
php
Copy code
$pattern = "/apple/";
$subject = "I have an apple.";
if (preg_match($pattern, $subject)) {
echo "Pattern found!";
}
○
2. preg_replace():
○ Purpose: Performs a search and replace using regular
expressions.
○ Syntax: preg_replace($pattern, $replacement, $subject,
$limit, &$count)
○ Description: Searches the string for a pattern and replaces
it with a specified replacement.
Example:
php
Copy code
$pattern = "/apple/";
$replacement = "orange";
$subject = "I like apple.";
$newString = preg_replace($pattern, $replacement, $subject);
17. I. II. III. Declare an associative array named “items” to store the key-value pairs (“Bread”,
30), (“Butter”, 30), (“Jam”, 35), (“Cheese”, 32).
Print the array using for each loop
Sort the array according to values maintaining the key-value relationships and print the sorted
key-value pairs.
PHP Program: Associative Array and Sorting
PHP Code:
php
Copy code
<?php
// Step I: Declare an associative array with key-value pairs
$items = array(
"Bread" => 30,
"Butter" => 30,
"Jam" => 35,
"Cheese" => 32
);
Output:
Original Array:
makefile
Copy code
Bread: 30
Butter: 30
Jam: 35
Cheese: 32
17. Design a HTML form to input a string and to display whether it is palindrome or not on form
submission using PHP script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Palindrome Checker</title>
</head>
<body>
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the input string
$inputString = $_POST['inputString'];
Explanation:
1. HTML Form:
○ The form uses the POST method to submit the input to the same page
(method="POST").
○ It contains a text input field (<input type="text" name="inputString"
id="inputString" required>) for the user to enter a string.
○ The submit button (<input type="submit" value="Check
Palindrome">) triggers the form submission.
2. PHP Script:
○ Form Submission: The $_SERVER["REQUEST_METHOD"] == "POST"
condition checks if the form has been submitted.
○ String Processing: The str_replace(' ', '', $inputString) function
removes spaces from the string, and strtolower() converts the string to
lowercase to handle case-insensitivity.
○ Palindrome Check: The strrev() function reverses the string, and then the
original string is compared with the reversed one. If they match, it's a palindrome;
otherwise, it's not.
○ Display Result: Based on the result, a message is displayed stating whether the
input string is a palindrome or not.
Example:
Input:
Output:
csharp
Copy code
'madam' is a palindrome!
Input:
● User enters: hello
Output:
csharp
Copy code
'hello' is not a palindrome.
18. Write a PHP script to search for a specific string pattern in a text.
To search for a specific string pattern within a text, you can use the preg_match() function,
which performs a regular expression match. It searches a string for a pattern and returns
whether the pattern is found or not.
Steps:
PHP Script:
php
Copy code
<?php
// Define the text and the pattern to search
$text = "The quick brown fox jumps over the lazy dog.";
$pattern = "fox"; // Pattern to search for
Explanation:
1. Text and Pattern:
○ $text is the string in which we want to search for a specific pattern.
○ $pattern is the string we want to search within the $text variable.
2. preg_match() Function:
○ preg_match() checks if the specified pattern exists in the text.
○ It returns 1 (true) if the pattern is found, and 0 (false) if it's not.
3. Output:
○ The script displays a message indicating whether the pattern was found in the
text.
Example:
Input:
● $text = "The quick brown fox jumps over the lazy dog."
● $pattern = "fox"
Output:
vbnet
Copy code
The string 'fox' was found in the text!
Input:
● $pattern = "cat"
Output:
vbnet
Copy code
The string 'cat' was not found in the text.