wp mod 3
wp mod 3
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: