0% found this document useful (0 votes)
16 views23 pages

wp mod 3

web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views23 pages

wp mod 3

web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

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

You might also like