0% found this document useful (0 votes)
13 views

2 - Chapter 2 - PHP

Uploaded by

Haymanot Aweke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

2 - Chapter 2 - PHP

Uploaded by

Haymanot Aweke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Introduction to PHP

Internet Programming II: Chapter 2

ADDIS ABABA SCIENCE AND TECHNOLOGY UNIVERSITY


Department of Software Engineering
Main Source: www.w3schools.com/php
Introduction
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• It is a widely-used, free and open source scripting language which is
executed on the server
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML
• PHP can:
• generate dynamic page content, collect form data, send and receive cookies,
encrypt data
• create, open, read, write, delete, and close files on the server
• add, delete, modify data in your database
• be used to control user-access
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
and it is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is easy to learn and runs efficiently on the server side

3/7/2023 2
Basic PHP Syntax
• A PHP script can be placed anywhere in the document. It starts with
<?php and ends with ?>
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
<!DOCTYPE html>
<html> Exam ple
<body>
<h1>My first PHP page</h1>
Output
<?php
echo "Hello World!";
?>

</body>
</html>

3/7/2023 3
PHP Comment
• Use // or # to add single line comment
• Use /*..*/ to add multiple line comment
Example: Comment
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiplelines
*/
?>
</body>
</html>

3/7/2023 4
PHP Variables
! Variables are "containers" for storing information
• In PHP, a variable starts with the $ sign, followed by the name of
the variable
• Example:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
• Accessing variable values:
<?php <?php
$txt = "W3Schools.com"; $txt = "W3Schools.com";
echo "I love $txt!"; echo "I love " . $txt . "!";
?> ?>

• PHP is a Loosely Typed Language

3/7/2023 5
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script
• The scope of a variable is the part of the script where
the variable can be referenced/used.
• PHP has three different variable scopes: local, global
and Static
• A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function
• A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that function

3/7/2023 6
PHP Variables Scope example
Example: Variable with global scope
Example: Variable with local scope
<?php
<?php
$x = 5; // global scope
function myTest() {
$x = 5; // local scope
function myTest() {
echo "<p>Variable x inside
// using x inside this
function is: $x</p>";
function will generate an error
}
echo "<p>Variable x inside
myTest();
function is: $x</p>";
}
// using x outside the function
myTest();
will generate an error
echo "<p>Variable x outside
echo "<p>Variable x outside
function is: $x</p>";
function is: $x</p>";
?>
?>

3/7/2023 7
PHP global Keyword
• A global variable can be accessed from within a
function using either global keywork or global array
Example: using global keyword
Example: using $GLOBALS[] array
<?php
<?php
$x = 5; $x = 5;
$y = 10; $y = 10;

function myTest() { function myTest() {


global $x, $y; $GLOBALS['y'] = $GLOBALS['x']
$y = $x + $y; + $GLOBALS['y'];
} }

myTest();
myTest(); echo $y; // outputs 15
echo $y; // outputs 15 ?>
?>

3/7/2023 8
PHP The static Keyword
• Normally, when a function is completed/executed, all of its
variables are deleted
• However, sometimes we want a local variable NOT to be
deleted. We need it for a further job
• To do this, use the static keyword when you first declare the
variable:
<?php
function myTest() {
static $x = 0;
echo $x; Output
$x++; 0
} 1
2
myTest();
myTest();
myTest();
?>

3/7/2023 9
PHP Constants
• A constant is an identifier (name) for a simple value
• The value cannot be changed during the script
• A valid constant name starts with a letter or
underscore (no $ sign before the constant name)
• Note: Unlike variables, constants are automatically
global across the entire script
• Syntax: define(name, value, case-insensitive)
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name
should be case-insensitive. Default is false

3/7/2023 10
PHP Constants cont’d
Example: constant with a case- Example: constant with a case-
sensitive name insensitive name
<?php <?php
define("GREETING", "Welcome to define("GREETING", "Welcome to
W3Schools.com!"); W3Schools.com!", true);
echo GREETING; echo greeting;
?> ?>

Example: Array constant


<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>

3/7/2023 11
PHP echo and print Statements
• With PHP, there are two basic ways to get output: echo and print
• The difference between echo and print are small:
• echo has no return value while print has a return value of 1 so it can be
used in expressions
• echo can take multiple parameters (although such usage is rare) while
print can take one argument
• echo is marginally faster than print
• Both can be used with or without parentheses:
• echo or echo()
• print or print()

Example: echo Example: print


<?php <?php
$txt = "Learn PHP"; $txt = "Learn PHP";
echo "<h2>" . $txt . "</h2>";
echo "This ", "string ", "was print "<h2>" . $txt . "</h2>";
", "made ", "with multiple print "Hello world!<br>";
parameters."; print "I'm about to learn PHP!";
?> ?>

3/7/2023 12
PHP Data Types
Data Type Description Example
String A sequence of characters, like "Hello world!" $y = 'Hello world!';
echo "<br>";
echo $y;
Integer A non-decimal number between - $x = 5985;
2,147,483,648 and 2,147,483,647 var_dump($x);
Float A number with a decimal point or a number in $x = 10.365;
exponential form var_dump($x);
Boolean Represents two possible states: TRUE or FALSE $x = true; or $y = false;
Array Stores multiple values in one single variable $cars = array("Volvo","BMW","Toyota");
var_dump($cars);
Objects Instances of user-defined classes that can store class bike {
both values and functions. They must be function model() {
explicitly declared. $model_name = "Royal Enfield";
echo "Bike Model: " .$model_name; }
}
$obj = new bike();
$obj -> model();
Resources Are not the exact data type in PHP. Basically, For example - a database call. It is an
these are used to store some function calls or external resource
references to external PHP resources.
3/7/20 3 13
Null 2 is a special data type that has only one value: NULL $nl = NULL;
PHP Operators
• Arithmetic Operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th


power

3/7/2023 14
PHP Operators cont’d
• Assignment Operators
Assignment Same as... Description

x=y x=y The left operand gets set to the value of the
expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

3/7/2023 15
PHP Operators cont’d
• Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of
the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are
not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is less
than, equal to, or greater than $y. Introduced
in PHP 7.
3/7/2023 16
PHP Operators cont’d
• Increment / Decrement Operators
Operator Name Description
++$x Pre- Increments $x by one, then returns
increment $x
$x++ Post- Returns $x, then increments $x by
increment one
--$x Pre- Decrements $x by one, then returns
decrement $x
$x-- Post- Returns $x, then decrements $x by
decrement one

3/7/2023 17
PHP Operators cont’d
• Logical Operators

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true,
but not both
&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true


! Not !$x True if $x is not true

3/7/2023 18
PHP Operators cont’d
• String Operators

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation


of $txt1 and
$txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2
assignment to $txt1

3/7/2023 19
PHP Operators cont’d
• Conditional Assignment Operators
Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE

?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.


The value of $x is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or is NULL, the
value of $x is expr2.
Introduced in PHP 7

3/7/2023 20
PHP if Statement
The if statement executes some code if one condition is true

Syntax
if (condition) {
code to be executed if condition is true;
}

Example
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

3/7/2023 21
PHP if...else Statement
• The if...else statement executes some code if a condition
is true and another code if that condition is false
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
3/7/2023 22
PHP if...elseif...else Statement
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition
is true;
} else { code to be executed if all conditions are false;}
Example
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

3/7/2023 23
PHP switch Statement
Use the switch statement to select one of many blocks of code
to be executed

Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

3/7/2023 24
PHP switch Statement
Example:
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

3/7/2023 25
PHP while Loop
• The while loop executes a block of code as long as the
specified condition is true
Syntax
while (condition is true) {
code to be executed;
}

Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

3/7/2023 26
PHP do...while Loop
• The do...while loop will always execute the block of code once, it will then
check the condition, and repeat the loop while the specified condition is
true
Syntax
do {
code to be executed;
} while (condition is true);

Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

3/7/2023 27
PHP for Loop
• The for loop is used when you know in advance how many
times the script should run

Syntax
for (init counter; test counter;
increment counter) {
code to be executed for each iteration;
}

Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

3/7/2023 28
PHP foreach Loop
• The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array
Syntax
foreach ($array as $value) {
code to be executed;
}

Example
<?php
$colors
= array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

3/7/2023 29
PHP Break and Continue
• PHP Break can be used to "jump out" of a switch
statement or a loop
• PHP Continue continue statement breaks one iteration
(in the loop), if a specified condition occurs, and
continues with the next iteration in the loop
Example: break Example: continue
<?php <?php
for ($x = 0; $x < 10; $x++) { for ($x = 0; $x < 10; $x++) {
if ($x == 4) { if ($x == 4) {
break; continue;
} }
echo "The number is: $x <br>"; echo "The number is: $x <br>";
} }
?> ?>

3/7/2023 30
PHP String Functions
Function Description Example
strlen() Return the length echo strlen(“Hello world!"); //outputs 12
of a string
str_word_count() Count words in a echo str_word_count("Hello world!");
string //outputs 2

strrev() Reverse a string echo strrev("Hello world!"); //outputs


!dlrow olleH
strpos() Search for a text echo strpos("Hello world!", "world");
within a string //outputs 6

str_replace() Replace text echo str_replace("world", "Dolly", "Hello


within a string world!"); //outputs Hello Dolly!

3/7/2023 31
PHP Numbers Functions
Function Description Example
is_int(), Checks if the type of a $x = 5985;
is_integer(), variable is integer var_dump(is_int($x)); bool(true)
is_long() $x = 59.85;
var_dump(is_int($x)); //bool(false)
is_float(), Checks if the type of a $x = 10.365;
is_double() variable is float var_dump(is_float($x)); //bool(true)
is_finite() Checks if a numeric value is $x = 1.9e411;
is_infinite() finite or infinite var_dump($x);

is_nan() Checks if a value is not a float(NAN)


number
is_numeric() function can be used to $x = "5985";
find whether a variable is var_dump(is_numeric($x)); //bool(true)
numeric

3/7/2023 32
PHP Casting Strings and Floats to
Integers
• The (int), (integer), or intval() function are used to
convert a value to an integer
<?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;

echo "<br>";

// Cast string to int


$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
?>

3/7/2023 33
PHP Math
Function Description Example
pi() Returns the value of PI echo(pi()); // returns 3.1415926535898
min() Used to find the lowest echo(min(0, 150, 30, 20, -8, -200)); //
value in a list of arguments returns -200
max() Used to find the highest echo(max(0, 150, 30, 20, -8, -200)); //
value in a list of arguments returns 150
abs() Returns the absolute echo(abs(-6.7)); // returns 6.7
(positive) value of a
number
sqrt() Function returns the echo(sqrt(64)); // returns 8
square root of a number
round() Rounds a floating-point echo(round(0.60)); // returns 1
number to its nearest echo(round(0.49)); // returns 0
integer
rand() Function generates a echo(rand());
random number echo(rand(10, 100)); // random
3/7/202
number between 10 and 100 inclusive 34
3
PHP Functions
• PHP has more than 1000 built-in functions, and in
addition you can create your own custom functions
• A user-defined function declaration starts with the
word function:
Syntax
function functionName() {
code to be executed;
}

Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

3/7/2023 35
PHP Functions cont’d
• Functions with arguments
<?php
function person($fname, $nationality = “Ethiopian”)
{
echo “Name: $fname Nationality:
$nationality.<br>";
}

person("Jani");
person("Hege");
person("Stale");
person("Kai Jim");
person("Borge");
?>
3/7/2023 36
PHP Functions cont’d
• Function return

Example
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

3/7/2023 37
PHP Return Type Declarations
• Like with the type declaration for function arguments, by
enabling the strict requirement, type declaration will throw
a "Fatal Error" on a type mismatch
• To declare a type for the function return, add a colon ( : )
and the type right before the opening curly ( { )bracket
when declaring the function
Example: different return and
Example
argument types
<?php declare(strict_types=1);
<?php declare(strict_types=1);
// strict requirement
// strict requirement
function addNumbers(float $a,
function addNumbers(float $a,
float $b) : float {
float $b) : int {
return $a + $b;
return (int)($a + $b);
}
}
echo addNumbers(1.2, 5.2);
echo addNumbers(1.2, 5.2);
?>
?>

3/7/2023 38
Passing Arguments by Reference
• In PHP, arguments are usually passed by value, which means:
• Copy of the value is used in the function and
• The variable that was passed into the function cannot be changed
• When a function argument is passed by reference,
• changes to the argument also change the variable that was passed in
• To turn a function argument into a reference, the & operator is
used:
Example
<?php
function addFive(&$value) {
$value += 5;
} Outp ut:
7
$num = 2;
addFive($num);
echo $num;
?>

3/7/2023 39
PHP Arrays
• Array can be created using array()
• Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
• There are three types of PHP arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more
arrays

3/7/2023 40
PHP Indexed Arrays
• There are two ways to create indexed arrays:
• Automatic indexing (index always starts at 0), like this:
• $cars = array("Volvo", "BMW", "Toyota");
• Manual indexing:
• $cars[0] = "Volvo";
• $cars[1] = "BMW";
• $cars[2] = "Toyota";
• Accessing array elements in both cases is similar
• Example to print BMW:
• echo $cars[1] ;

3/7/2023 41
PHP Associative Arrays
• Associative arrays are arrays that use named keys
that you assign to them
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
• The named keys can then be used in a script:
echo "Peter is " . $age['Peter'] . " years old.";

3/7/2023 42
PHP Array Functions
• array_intersect() function returns the intersection of two array. In
other words, it returns the matching elements of two array.
• Syntax: array array_intersect ( array $array1 , array $array2 [, array $... ] )
• array_search() function searches the specified value in an array. It
returns key if search is successful
• Syntax: mixed array_search ( mixed $needle , array $haystack [, bool
$strict = false ] )
Example: array_intersect()
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
Example: array_s earch()
{
echo "$n<br />"; <?php
} $season=array("su mmer","winter","spring","autumn"
?> );
$key=array_searc h("spring",$season);
echo $key;
?>
3/7/2023 43
PHP Array Functions cont’d
• array_reverse() function returns an array containing elements in
reversed order
• Syntax: array array_reverse ( array $array [, bool $preserve_keys = false ] )
• sort() function sorts all the elements in an array.
• Syntax: bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example: array_reverse()
<?php
$season=array("summer","winter","spring","autumn");

$reverseseason=array_reverse($season);
Example: so rt()
foreach( $reverseseason as $s )
{ <?php
echo "$s<br />"; $season=arr ay("summer","winter","spring","autumn
} ");
?> sort($season );
foreach( $season as $s )
{
echo "$s<br />";
}
?>

3/7/2023 44
PHP Global Variables - Superglobals
• Some predefined variables in PHP are "superglobals“
• which means that they are always accessible, regardless of scope
• you can access them from any function, class or file without having
to do anything special
• The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION

3/7/2023 45
PHP Global Variables –Superglobals cont’d
Superglobal Variable Description
$GLOBALS Stores all the global scope variables.

$_SERVER Stores information about the server and execution


environment.

$_GET Stores HTTP GET variables.


$_POST Stores HTTP POST variables.
$_FILES Stores HTTP file upload variables.
$_ENV Stores environment variables.
$_COOKIE Stores HTTP Cookies.
$_SESSION Stores session variables.
$_REQUEST Stores request variables
($_GET, $_POST and $_COOKIE variables)

3/7/2023 46
PHP Regular Expressions
• In PHP, regular expressions are strings composed of
delimiters, a pattern and optional modifiers
• E.g. $exp = "/w3schools/i";
• In the example above, / is the delimiter, w3schools is the
pattern that is being searched for, and i is a modifier that
makes the search case-insensitive.
• The delimiter can be any character that is not a letter,
number, backslash or space.
• The most common delimiter is the forward slash (/), but
when your pattern contains forward slashes it is convenient
to choose other delimiters such as # or ~.
Regular Expression Functions
• The preg_match(), preg_match_all() and preg_replace()
functions are some of the most commonly used PHP
regular expression functions

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the
string, which may also be 0
preg_replace() Returns a new string where matched patterns have been
replaced with another string
Regular Expression Functions examples
Example: Using preg_match() Example: Using preg_match_all()
<!DOCTYPE html> <?php
$str = "The rain in SPAIN falls mainly
<html>
Output: on the plains."; Output:
<body> $pattern = "/ain/i";
1 4
echo preg_match_all($pattern,
<?php $str);
$str = "Visit W3Schools"; ?>
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); Example: Using preg_replace()
?> <?php Output:
$str = "Visit Microsoft!"; Visit W3Schools!
</body> $pattern = "/microsoft/i";
</html> echo preg_replace($pattern, "W3Schools",
$str);
?>
Regular Expression cont’d
• Modifiers: can change how a search is performed
Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for the beginning
or end of a string will match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns

• Patterns: brackets are used to find a range of characters


Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters (characters with a
special meaning)
Metacharacter Description
| Find a match for any one of the patterns separated by | as in:
cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or
at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal
number xxxx
Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's

Grouping:
• You can use parentheses ( ) to apply quantifiers to entire patterns
• They also can be used to select parts of the pattern to be used as a match
<?php
$str = "Apples and bananas.";
Output:
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1 1
?>

You might also like