Mod 3 Complete

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Mod 3

3.1 Building blocks of PHP-Variables, Data Types simple PHP program


3.2 Converting between Data Types, Operators and Expressions -Flow Controlfunctions
3.3 Control Statements -Working with Functions
3.4 Initialising and Manipulating Arrays- Objects
3.5 Working with Strings-String processing with Regular expression, Pattern Matching
3.6 Form processing and Business Logic

PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language


designed for web development but also used as a general-purpose programming language. It is
especially known for its ability to create dynamic web pages that interact with databases and
other back-end services. PHP code is executed on the server, and the result is sent to the
client’s browser as plain HTML.

Key Features of PHP:

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 PHP block

echo "Hello, World!";

?>

THE STRUCTURE OF PHP: USING COMMENTS

// This is a comment
$x += 10; // Increment $x by 1

<?php

/*this is a section of mutliline comments /*

?>

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”)
?>

3.1 Building blocks of PHP-Variables, Data Types simple PHP program

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

CONVERTING BETWEEN DATA TYPES


● PHP variables are loosely typed—they can contain different types of data at different
times.
● Type conversions can be performed using function settype (p. 667). This function takes
two arguments—a variable whose type is to be changed and the variable’s new type.
● Variables are automatically converted to the type of the value they’re assigned.
● Function gettype (p. 669) returns the current type of its argument.
● Calling function settype can result in loss of data. For example, doubles are truncated
when they’re converted to integers.
● When converting from a string to a number, PHP uses the value of the number that
appears at the beginning of the string. If no number appears at the beginning, the string
evaluates to 0.
● Another option for conversion between types is casting (or type casting, p. 669). Casting
does not change a variable’s content—it creates a temporary copy of a variable’s value
in memory.
● The concatenation operator combine multiple strings.
● A print statement split over multiple lines prints all the data that’s enclosed in its
parentheses.

2. CONVERTING DATA TYPES USING TYPE JUGGLING

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.

For example: 1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and $num is a
variable.

PHP Operators can be categorized in the following forms:


o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators

We can also categorize operators on behalf of operands.

They can be categorized in 3 forms:


o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

FLOW CONTROL FUCNTIONS

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

Executes code if the condition is true.

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

Provides an alternative block of code if the condition is false.

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

Checks multiple conditions in sequence.

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

Evaluates a variable against multiple possible values.

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

Loops execute a block of code multiple times, depending on conditions.

a. while Loop

Executes as long as the condition is true.

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

Executes the block at least once before checking the condition.

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

Runs a block of code for a fixed number of iterations.

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

Used to iterate over arrays.

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

Exits the current loop or switch statement.

Example:

php
Copy code
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo "Number: $i\n";
}

b. continue

Skips the current iteration and moves to the next.

Example:

php
Copy code
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo "Number: $i\n";
}

4. Ternary Operator

A shorthand for if-else.

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

Returns the first non-null value.

Syntax:

php
Copy code
$result = $var1 ?? $var2;

Example:

php
Copy code
$username = $_GET['username'] ?? 'Guest';
echo "Hello, $username";

WORKING WITH FUNCTIONS IN PHP

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.

2. Types of Functions in PHP

1. Built-in Functions: Predefined by PHP (e.g., strlen(), array_push(), date()).


2. User-defined Functions: Custom functions created by developers.

Defining and Calling Functions

a. Syntax to Define a Function

function functionName(parameters) {
// Code to execute
return value; // Optional
}

b. Calling a Function
functionName(arguments);

Example 1: Simple Function


function greet() {
echo "Hello, World!";
}

greet(); // Output: Hello, World!

Example 2: Function with Parameters

function addNumbers($a, $b) {


return $a + $b;
}

$result = addNumbers(5, 10);


echo "Sum: $result"; // Output: Sum: 15

Example 3: Function with Default Parameters


function greetUser($name = "Guest") {
echo "Hello, $name!";
}

greetUser(); // Output: Hello, Guest!


greetUser("Alice"); // Output: Hello, Alice!

Example 4: Function Returning Values


function multiply($x, $y) {
return $x * $y;
}

echo multiply(4, 5); // Output: 20

3.4 Initialising and Manipulating Arrays- Objects


Explain how a PHP array differs from an array in C? List the different ways to create an array in
PHP with an example. Explain any 4 functions that deal with PHParrays.

PHParrays and arrays in C are quite different in terms of their structure, behavior, and flexibility.

1. Type of Data Stored:


○ PHPArrays:PHParrays are dynamic and can hold elements of different types (integers, strings,
objects, etc.) in the same array. It can also be an associative array where elements are
accessed via string keys.
○ CArrays:InC,arrays are fixed-size and homogeneous, meaning that all elements in the array
must be of the same data type, and the size is defined at the time of array declaration.

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).

Ways to Create an Array in PHP

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.

$array1 = array("a" => "red", "b" => "green");


$array2 = array("c" => "blue", "d" => "yellow");
$result = array_merge($array1, $array2);
print_r($result);

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");

array_push($stack, "cherry", "orange");


print_r($stack);
Output: Array ( [0] => apple [1] => banana [2] => cherry [3] => orange )

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 )

4. in_array(): This function checks whether a value exists in an array.

$fruits = array("Apple", "Banana", "Orange");


if (in_array("Banana", $fruits))
{ echo "Banana is in the array!";
} else {
echo "Banana is not in the array!"; }

Output: Banana is in the array

3.5 Working with Strings-String processing with Regular expression, Pattern Matching

STRING PROCESSING WITH REGULAR EXPRESSIONS

● 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

1. In addition to literal characters, regular expressions can include metacharacters, such as


^, $, and ., that specify patterns.
2. The caret (^) metacharacter matches the beginning of a string (line 23), while the dollar
sign ($) matches the end of a string (line 27).
3. The period (.) metacharacter matches any single character except newlines, but can be
made to match newlines with the s modifier.
4. Line 23 searches for the pattern "Now" at the beginning of $search.
5. Line 27 searches for "Now" at the end of $search.
6. Note that Now$ is not a variable—it’s a pattern that uses $ to search for the characters
"Now" at the end of a string.
7. Line 31, which contains a bracket expression, searches (from left to right) for the first
word ending with the letters ow.
8. Bracket expressions are lists of characters enclosed in square brackets ([]) that match
any single character from the list.
9. Ranges can be specified by supplying the beginning and the end of the range separated
by a dash (-).
10. For instance, the bracket expression [a-z] matches any lowercase letter and [A-Z]
matches any uppercase letter.
11. In this example, we combine the two to create an expression that matches any letter.
12. The \b before and after the parentheses indicates the beginning and end of a word,
respectively—in other words, we’re attempting to match whole words.
13. The expression [a-zA-Z]*ow inside the parentheses (line 31) represents any word
ending in ow.
14. The quantifier * matches the preceding pattern zero or more times.
15. Thus, [a-zA-Z]*ow matches any number of letters followed by the literal characters
ow.
16. Quantifiers are used in regular expressions to denote how often a particular character or
set of characters can appear in a match.
17. Some PHP quantifiers are listed in Fig. 19.10.

Quantifier Table:

Some Regular Expression Quantifiers


{n}: Matches exactly n times.
{m,n}: Matches between m and n times, inclusive.
{n,}: Matches n or more times.

+: Matches one or more times (same as {1,}).


*: Matches zero or more times (same as {0,}).
?: Matches zero or one time (same as {0,1}).

FINGING MATCHES

Third Argument in preg_match:

● The optional third argument is an array that stores matches to the regular expression.

Parenthetical Sub-Expressions:

● When the regular expression includes parenthetical sub-expressions, preg_match


stores matches for each in the array.
● Index 0 contains the match for the entire pattern.
● Subsequent indices (1, 2, etc.) store matches for the parenthetical sub-expressions, in
left-to-right order.

Uninitialized Array Elements:

● If a parenthetical pattern is not encountered, the corresponding array element remains


uninitialized.
Example from Line 31:

● "Now" is stored in $match[1] (the first parenthetical pattern).


● Since it’s the only parenthetical pattern, it is also stored in $match[0].

Finding Multiple Instances of a Pattern:

● preg_match only returns the first instance of a pattern in a string.


● To find multiple instances, you must:
1. Make multiple calls to preg_match.
2. Remove matched instances from the string before calling the function again.

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

1. Pattern in Line 38:

○ The pattern /\b(t[[:alpha:]]+)\b/i matches any word starting with the


character t, followed by one or more letters.
○ The pattern uses the character class [[:alpha:]], which is equivalent to
[a-zA-Z].
2. Character Classes:

○ Character classes define sets of characters to match in a regular expression.


○ Some common classes are:
■ alnum: Alphanumeric characters ([a-zA-Z0-9]).
■ alpha: Word characters ([a-zA-Z]).
■ digit: Digits ([0-9]).
■ space: White space characters.
■ lower: Lowercase letters.
■ upper: Uppercase letters.
3. Syntax for Character Classes:

○ Character classes are enclosed by delimiters [: and :].


○ For example, [[:alpha:]] matches any single letter.
4. Combining Character Classes:

○ Adjacent character classes within brackets combine their sets.


○ Examples:
■ [[:upper:][:lower:]]*: Matches all strings of uppercase and
lowercase letters in any order.
■ [[:upper:]][[:lower:]]*: Matches strings with a single uppercase
letter followed by any number of lowercase letters.
■ ([[:upper:]][[:lower:]])*: Matches strings that alternate between
uppercase and lowercase characters, starting with uppercase.
5. Word Boundaries (\b):

○ The \b in the pattern specifies word boundaries, ensuring the match is a whole
word.
6. Case-Insensitive Matching:

○ The i flag in the pattern makes the match case insensitive.

FINDING MUTLIPLE INSTANCE OF A PATTERN

1. Quantifier +:

○ The quantifier + matches one or more consecutive instances of the preceding


expression.
2. Storing Matches:

○ The result of the match is stored in $match[1].


3. Printing Matches:

○ Once a match is found, it is printed (e.g., in line 40).


4. Removing Matched Instances:

○ The function preg_replace is used to remove the matched string from the
original string.
5. Arguments of preg_replace:

○ preg_replace takes three arguments:


1. The pattern to match.
2. A string to replace the matched string.
3. The string to search.
6. Process of Removing and Matching:

○ 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

1. Write a php program to check whether a number is prime or not


<?php
// Function to check if a number is prime
function isPrime($number) {
// If the number is less than 2, it's not prime
if ($number < 2) {
return false;
}

// Loop from 2 to the square root of the number


for ($i = 2; $i <= sqrt($number); $i++) {
// If the number is divisible by any number other than 1 and
itself
if ($number % $i == 0) {
return false;
}
}

// If no factors are found, it's a prime number


return true;
}

// 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.";
}
?>

2. Explain any 5 string handling function used in php


3. How does a PHP array differ from an array in C? List the different ways to create
an array in PHP with an example. Explain any 4 functions that deals with PHP
array.
4. During the process of fetching a web page from a web server to a client browser,
at what point does an embedded PHP script get executed. What are the two modes
that the PHP processor operates in? Explain

Execution of an Embedded PHP Script

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

The PHP processor operates in two primary modes:

a. Scripting Mode

● This is the most common mode.


● PHP is embedded within HTML files to generate dynamic content.

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.

b. Command-Line Interface (CLI) Mode

● 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

This will execute script.php directly in the terminal.

● 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.

PHP is a dynamically typed language, meaning:

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.

2. Difference between implode and explode Functions


The implode and explode functions in PHP are used to work with strings and arrays. Here’s a
detailed comparison:

Aspect implode() explode()

Purpos Combines elements of an array into a Splits a string into an array based on a
e single string. delimiter.

Input An array and a string delimiter. A string and a string delimiter.

Output A single string. An array of substrings.

Usage Used to create a string from an array Used to parse a string into parts.
(e.g., CSV).
3. Examples

implode() Example

Combines an array into a single string using a delimiter:

php
Copy code
$array = ["apple", "banana", "cherry"];
$string = implode(", ", $array); // Combines array elements with ", "
echo $string;
// Output: apple, banana, cherry

explode() Example

Splits a string into an array using a delimiter:

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 )

6. Convert the following to equivalent PHP statements :


(i) Declare an associative array named “ages” to store the key-value pairs (“Alice”, 30), (“Bob”,
30), (“Harry”, 35), (“Mary”, 32).
(ii) Modify the value associated with the key “Mary” to 28.
(iii) Sort the array according to values maintaining the key-value relationships and print the
sorted key-value pairs.
(iv) Delete the entry identified by the key “Bob”.

(i) declare an associative array named”ages”


To declare an associative array named ages to store the specified key-value paires:
7. Write a PHP program to store the name and roll no of 10 students in an Associative Array
and Use for each loop to process the array and Perform a sort, r sort and k sort in the array.
Illustrate with suitable output data

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";

// Step 3: Perform a sort (value-based sorting)


asort($students);
echo "Array after asort (Sorted by Names in Ascending Order):\n";
foreach ($students as $rollNo => $name) {
echo "Roll No: $rollNo, Name: $name\n";
}
echo "\n";

// Step 4: Perform a rsort (reverse value sorting)


// Note: rsort() re-indexes the array; to preserve keys we use
arsort()
arsort($students);
echo "Array after arsort (Sorted by Names in Descending Order):\n";
foreach ($students as $rollNo => $name) {
echo "Roll No: $rollNo, Name: $name\n";
}
echo "\n";

// Step 5: Perform a ksort (key-based sorting)


ksort($students);
echo "Array after ksort (Sorted by Roll Numbers in Ascending
Order):\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

Array after asort (Sorted by Names in Ascending Order):


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

Array after arsort (Sorted by Names in Descending Order):


Roll No: 110, Name: Jack
Roll No: 109, Name: Ivy
Roll No: 108, Name: Hannah
Roll No: 107, Name: Grace
Roll No: 106, Name: Frank
Roll No: 105, Name: Eve
Roll No: 104, Name: David
Roll No: 103, Name: Charlie
Roll No: 102, Name: Bob
Roll No: 101, Name: Alice

Array after ksort (Sorted by Roll Numbers in Ascending Order):


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

// Determine if the number is odd or even


if ($number % 2 == 0) {
echo "<div class='result'>The number
<strong>$number</strong> is <span style='color:
green;'>Even</span>.</div>";
} else {
echo "<div class='result'>The number
<strong>$number</strong> is <span style='color:
red;'>Odd</span>.</div>";
}
}
?>
</div>
</body>
</html>
Explanation of Code (Step-by-Step):

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:

1. Checking Form Submission:


○ The $_SERVER["REQUEST_METHOD"] ensures the PHP code executes only
when the form is submitted.
2. Retrieving and Validating Input:
○ The $_POST['number'] retrieves the input from the form.
○ intval() is used to ensure the input is treated as an integer.
3. Odd or Even Logic:
○ The modulo operator (%) checks whether the number is divisible by 2.
○ If number % 2 == 0, the number is even, otherwise, it is odd.
4. Displaying Results:
○ Results are dynamically displayed with appropriate colors (green for even, red for
odd).

Output Example:

Case 1: Input = 7

User Action: Enter 7 and click "Check".


Output: "The number 7 is Odd."

Case 2: Input = 10

User Action: Enter 10 and click "Check".


Output: "The number 10 is Even."

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

// Use a do-while loop to calculate the sum of integers from 1 to 100


do {
$sum += $number; // Add the current number to the sum
$number++; // Increment the number
} while ($number <= 100); // Continue the loop while the number is
less than or equal to 100

// Display the result


echo "The sum of positive integers from 1 to 100 is: $sum";
?>

Explanation of Code (Step-by-Step):

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 Program to Check if a Number is an Armstrong Number

An Armstrong number (also known as a narcissistic number) is a number


that is equal to the sum of its digits raised to the power of the
number of digits. For example, 153 is an Armstrong number because
13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153.

PHP Code:
php
Copy code
<?php
// Input: The number to check
$number = 153; // Change this to test with other numbers

// Step 1: Initialize variables


$sum = 0;
$temp = $number;
$numDigits = strlen((string)$number); // Count the number of digits

// Step 2: Check if the number is Armstrong


while ($temp > 0) {
$digit = $temp % 10; // Extract the last digit
$sum += pow($digit, $numDigits); // Add the digit raised to the
power of the number of digits
$temp = intval($temp / 10); // Remove the last digit
}

// Step 3: Compare the sum with the original number


if ($sum == $number) {
echo "$number is an Armstrong number.";
} else {
echo "$number is not an Armstrong number.";
}
?>
Output
Input: 153
Output: 153 is an Armstrong number.
Input: 123
Output: 123 is not an Armstrong number.

10.Explain the loops used in PHP with example.

Loops in PHP

Loops are used in PHP to execute a block of code repeatedly, either


for a fixed number of times or until a condition is met. PHP supports
the following types of loops:

1. for Loop

The for loop is used when the number of iterations is known in


advance.

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

The foreach loop is used specifically for iterating over arrays. It


loops through each element in an array and assigns it to a variable.

Syntax:

php
Copy code
foreach ($array as $value) {
// Code to be executed
}

Example:

php
Copy code
<?php
// Define an array
$colors = ["Red", "Green", "Blue"];

// Loop through the array


foreach ($colors as $color) {
echo "Color: $color<br>";
}
?>
Output:

less
Copy code
Color: Red
Color: Green
Color: Blue

11. List out the sorting functions for Arrays in PHP. Illustrate with
suitable examples.

List of Array Sorting Functions:

1. sort(): Sorts an array in ascending order by values.


2. rsort(): Sorts an array in descending order by values.
3. asort(): Sorts an array in ascending order by values while maintaining key-value association.
4. arsort(): Sorts an array in descending order by values while maintaining key-value
association.
5. ksort(): Sorts an array in ascending order by keys.
6. krsort(): Sorts an array in descending order by keys.

Examples:

1. sort() - Ascending Order by Values


php
Copy code
<?php
$array = [3, 1, 4, 1, 5];
sort($array);
print_r($array);
?>

Output:

css
Copy code
Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )

2. rsort() - Descending Order by Values


php
Copy code
<?php
$array = [3, 1, 4, 1, 5];
rsort($array);
print_r($array);
?>

Output:

css
Copy code
Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 )

3. asort() - Ascending Order by Values (Maintain Keys)


php
Copy code
<?php
$array = ["b" => 3, "a" => 1, "c" => 4];
asort($array);
print_r($array);
?>

Output:

css
Copy code
Array ( [a] => 1 [b] => 3 [c] => 4 )

4. arsort() - Descending Order by Values (Maintain Keys)


php
Copy code
<?php
$array = ["b" => 3, "a" => 1, "c" => 4];
arsort($array);
print_r($array);
?>

Output:

css
Copy code
Array ( [c] => 4 [b] => 3 [a] => 1 )

5. ksort() - Ascending Order by Keys


<?php
$array = ["b" => 3, "a" => 1, "c" => 4];
ksort($array);
print_r($array);
?>

Output:

Array ( [a] => 1 [b] => 3 [c] => 4 )

6. krsort() - Descending Order by Keys


<?php
$array = ["b" => 3, "a" => 1, "c" => 4];
krsort($array);
print_r($array);
?>

Output:

Array ( [c] => 4 [b] => 3 [a] => 1 )

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.

Purpose of $_GET and $_POST in PHP

● $_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.

PHP Script to Collect Form Data and Perform Calculations

The script demonstrates:

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.

HTML Form (Input Section)


html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body>
<h2>Enter Two Numbers</h2>
<form action="arithmetic_operations.php" method="GET">
<label for="num1">Number 1:</label>
<input type="text" id="num1" name="num1" required><br><br>

<label for="num2">Number 2:</label>


<input type="text" id="num2" name="num2" required><br><br>

<input type="submit" value="Calculate">


</form>
</body>
</html>

PHP Script (arithmetic_operations.php)


php
Copy code
<?php
// Check if form data is submitted
if (isset($_GET['num1']) && isset($_GET['num2'])) {
// Retrieve input values from $_GET
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];

// Convert inputs to integers for calculations


$num1 = (int)$num1;
$num2 = (int)$num2;

// Perform arithmetic operations


$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;

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

Case 1: Inputs 5 and 3

When num1 = 5 and num2 = 3, the output will be:

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

Case 2: No Inputs Provided

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.

13.List six primitive data types used in PHP?

Six Primitive Data Types in PHP

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");

14.Give 3 string functions used in PHP associated with removal of whitespaces?


How will they differ each other?

String Functions in PHP for Removal of Whitespaces

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);

● $character_mask: (optional) A list of characters to be removed. By default, it removes


spaces, tabs, and newlines.

Example:

php
Copy code
<?php
$string = " Hello World! ";
$result = trim($string);
echo $result; // Output: "Hello World!"
?>

Explanation:

● Removes whitespace from the beginning and end of the string.


2. ltrim()

Purpose: Removes whitespace (or other characters) from the beginning (left side) of the string
only.

Syntax:

php
Copy code
ltrim($string, $character_mask);

● $character_mask: (optional) A list of characters to be removed from the left side. By


default, it removes spaces, tabs, and newlines.

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:

1. Create a function that accepts a number as input.


2. Calculate the factorial using a loop or recursion.
3. Return the result to be displayed.

PHP Program:
php
Copy code
<?php
// Function to calculate the factorial
function factorial($num) {
// Initialize the result variable
$result = 1;

// Check if the number is 0 or negative


if ($num < 0) {
return "Factorial is not defined for negative numbers.";
} elseif ($num == 0) {
return 1; // 0! is 1
}

// Loop to calculate the factorial


for ($i = 1; $i <= $num; $i++) {
$result *= $i; // Multiply result by i
}

// Return the calculated factorial


return $result;
}

// Input number (you can replace this with user input in a form)
$number = 5; // Example number

// Call the factorial function and print the result


echo "The factorial of $number is: " . factorial($number);
?>

Explanation of the Code:

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:

For an input of 5, the output will be:

csharp
Copy code
The factorial of 5 is: 120

For an input of 0, the output will be:

csharp
Copy code
The factorial of 0 is: 1

For an input of -3, the output will be:

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. Searching for patterns: Find specific text patterns in a string.


2. Validation: Validate input like email addresses, phone numbers,
or passwords.
3. String replacement: Replace certain patterns in a string with new
text.
4. Text extraction: Extract specific portions of a string based on a
pattern.

Regular expressions are highly efficient for complex string


manipulation tasks, making them indispensable in many web
applications, especially for form validation, data parsing, and
searching.

3 Components of a Regular Expression:

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.

Two Perl-Compatible Regular Expression (PCRE) Functions in


PHP:

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);

○ echo $newString; // Output: I like orange.

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

Below is a PHP program that:

1. Declares an associative array named items to store the key-value pairs.


2. Prints the array using a foreach loop.
3. Sorts the array according to values while maintaining the key-value relationships.
4. Prints the sorted key-value pairs.

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
);

// Step II: Print the array using a foreach loop


echo "<h3>Original Array:</h3>";
foreach ($items as $key => $value) {
echo "$key: $value<br>";
}

// Step III: Sort the array according to values maintaining the


key-value relationships
asort($items); // Sort the array in ascending order according to the
values

// Print the sorted array


echo "<h3>Sorted Array (by values):</h3>";
foreach ($items as $key => $value) {
echo "$key: $value<br>";
}
?>
Explanation:

1. Associative Array Declaration:


○ An associative array named $items is created with the key-value pairs:
■ "Bread" => 30
■ "Butter" => 30
■ "Jam" => 35
■ "Cheese" => 32
2. Printing the Array Using foreach:
○ The foreach loop is used to print all key-value pairs in the associative array. It
iterates through each element, printing the key and corresponding value.
3. Sorting the Array:
○ The function asort() is used to sort the array based on its values while
maintaining the key-value relationship.
○ After sorting, the foreach loop is used again to print the sorted array.

Output:

Original Array:
makefile
Copy code
Bread: 30
Butter: 30
Jam: 35
Cheese: 32

Sorted Array (by values):


makefile
Copy code
Bread: 30
Butter: 30
Cheese: 32
Jam: 35

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>

<!-- HTML Form to input string -->


<h2>Palindrome Checker</h2>
<form method="POST">
<label for="inputString">Enter a string:</label>
<input type="text" name="inputString" id="inputString"
required>
<input type="submit" value="Check Palindrome">
</form>

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the input string
$inputString = $_POST['inputString'];

// Remove spaces and convert to lowercase for accurate


comparison
$processedString = strtolower(str_replace(' ', '',
$inputString));

// Check if the string is a palindrome


if ($processedString == strrev($processedString)) {
echo "<h3>'$inputString' is a palindrome!</h3>";
} else {
echo "<h3>'$inputString' is not a palindrome.</h3>";
}
}
?>
</body>
</html>

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:

● User enters: madam

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.

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:

1. Define the text and the string pattern to search for.


2. Use preg_match() to search for the pattern.
3. Display the result if the pattern is found.

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

// Search for the pattern in the text using preg_match


if (preg_match("/$pattern/", $text)) {
echo "The string '$pattern' was found in the text!";
} else {
echo "The string '$pattern' was not found in the text.";
}
?>

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.

You might also like