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

Unit II (1)

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

Unit II (1)

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

Unit II

Control Structures
Conditional statements
PHP if else statement is used to test condition.
There are various ways to use if statement in
PHP.

In PHP, there are 4 different types of Conditional


Statements.
1.if statements
2.if...else statements
3.if...elseif...else statements
4.switch statement
Nested if…
<?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!";
}
?>
PHP Loops

Often when you write code, you want the same block of code to run over
and over again a certain number of times.

So, instead of adding several almost equal code-lines in a script, we can


use loops.

Loops are used to execute the same block of code again and again,
as long as a certain condition is true.

In PHP, we have the following loop types:

•while - loops through a block of code as long as the specified condition is


true
•do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
•for - loops through a block of code a specified number of times
•foreach - loops through a block of code for each element in an array
PHP for loop
The for loop - Loops through a block of code a specified number of times.

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

Parameters:
•init counter: Initialize the loop counter value
•test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
•increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:

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

Example Explained

•$x = 0; - Initialize the loop counter ($x), and set the start value to 0

•$x <= 10; - Continue the loop as long as $x is less than or equal to 10

•$x++ - Increase the loop counter value by 1 for each iteration


This example counts to 100 by tens:

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

Example Explained

•$x = 0; - Initialize the loop counter ($x), and set the start value to 0

•$x <= 100; - Continue the loop as long as $x is less than or equal to
100

•$x+=10 - Increase the loop counter value by 10 for each iteration


Exercise:

Create a loop that runs from 0 to 9.


PHP foreach Loop

The foreach loop - Loops through a block of code for each element in an
array.

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;
}
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
PHP foreach Loop

Examples

The following example will output the values of the given array
($colors):

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

foreach ($colors as $value) {


echo "$value <br>";
}
?> red
green
blue
yellow
PHP foreach Loop

The following example will output both the keys and the values of the
given array ($age):

<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val)


{
echo "$x = $val<br>";
}
?> Peter = 35
Ben = 37
Joe = 43
The 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;
}
The example below displays the numbers from 1 to 5:

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

•$x = 1; - Initialize the loop counter ($x), and set the start value to 1
•$x <= 5 - Continue the loop as long as $x is less than or equal to 5
•$x++; - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
The number is: 0
The number is: 10
The number is: 20
<?php
The number is: 30
$x = 0;
The number is: 40
The number is: 50
while($x <= 100)
The number is: 60
{
The number is: 70
echo "The number is: $x <br>";
The number is: 80
$x+=10;
The number is: 90
}
The number is: 100
?>

•$x = 0; - Initialize the loop counter ($x), and set the start
value to 0
•$x <= 100 - Continue the loop as long as $x is less than or
equal to 100
•$x+=10; - Increase the loop counter value by 10 for each
iteration
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);
The example below first sets a variable $x to 1 ($x = 1). Then, the do
while loop will write some output, and then increment the variable $x
with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to
5:

<?php
$x = 1;

do
{
echo "The number is: $x <br>";
$x++;
}
The number is: 1
while ($x <= 5);
The number is: 2
?>
The number is: 3
The number is: 4
The number is: 5
Note: In a do...while loop the condition is tested AFTER executing the
statements within the loop.

This means that the do...while loop will execute its statements at least
once, even if the condition is false. See example below.

This example sets the $x variable to 6, then it runs the loop, and then
the condition is checked:

<?php
$x = 6;

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

OUTPUT????
Exercise:

Output $i as long as $i is less than 6.


PHP Break

It is used to "jump out" of a switch statement.


The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

<?php
for ($x = 0; $x < 10; $x++)
{
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?> The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue
The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 4:

<?php The number is: 0


for ($x = 0; $x < 10; $x++) The number is: 1
{ The number is: 2
if ($x == 4) The number is: 3
{ The number is: 5
continue; The number is: 6
} The number is: 7
echo "The number is: $x <br>"; The number is: 8
} The number is: 9
?>
Break and Continue in While Loop
You can also use break and continue in while loops:

<?php
$x = 0;

while($x < 10)


The number is: 0
{
The number is: 1
if ($x == 4)
The number is: 2
{
The number is: 3
break;
}
echo "The number is: $x <br>";
$x++;
}
?>
Exit statement
The exit() function in PHP is an inbuilt function
which is used to output a message and terminate
the current script. The exit() function only
terminates the execution of the script.

Syntax
exit(message)

Example
<?php
$site = "https://paiza.io/en/projects/new?
language=php/";
fopen($site,"r")
or exit("Unable to connect to $site");
Die Statement
The die() is an inbuilt function in PHP. It is used to
print message and exit from the current php
script. It is equivalent to exit() function in PHP.

Syntax
die(message)

Example
<?php
$site = "https://paiza.io/en/projects/new?
language=php";
fopen($site,"r")
or die("Unable to connect to $site");
Die and Exit

•In php both die() and exit() are equivalent


functions.
•Basically die is used to throw an exception
while exit is not, it is only used to exit the
process.
•The die() function is used to print the
message and exit the script or it may be used
to print alternate message.
HTML <form> action Attribute

On submit, send the form-data to a file named "action_page.php" (to


process the input):

The action attribute specifies where to send the form-data when a form is
submitted.

<form action="URL">

<form action="" method="post">


<input type="number" name="year" />
<input type="submit" />
</form>
PHP $_POST is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="post". $_POST is also widely
used to pass variables.

PHP is_numeric() Function

is_numeric — Finds whether a variable is a number or a numeric


string

is_numeric(variable);

if(!is_numeric($year))
Php arrays
• PHP array is used to hold multiple values of
similar type in a single variable.
Advantage of PHP Array

• Less Code: We don't need to define multiple


variables.
• Easy to traverse: By the help of single loop, we
can traverse all the elements of an array.
• Sorting: We can sort the elements of array.
PHP Array Types

• There are 3 types of array in PHP.


• Indexed Array
• Associative Array
• Multidimensional Array
PHP Indexed Array

• PHP index is represented by number which


starts from 0.
• We can store number, string and object in the
PHP array.
• All PHP array elements are assigned to an
index number by default.
an associative array is a type of array where the keys are
strings or integers, and each key is associated with a
specific value. Unlike indexed arrays, where the keys are
numeric indices, associative arrays use meaningful keys
to access values.
PHP Multidimensional Array

• PHP multidimensional array is also known as


array of arrays.
• It allows you to store tabular data in an array.
PHP multidimensional array can be
represented in the form of matrix which is
represented by row * column.
PHP Array Functions

• Array()
• Count()
• Sort()
• array_reverse()
• array_search()
PHP array() Function

The array() function is used to create a PHP array. This function can be used to
create indexed arrays or associative arrays. PHP arrays could be single
dimensional or multi-dimensional.

Syntax

Syntax to create PHP indexed arrays:


$a = array(value1, value2, value3, ...)

Syntax to create PHP associative arrays:


$a = array(key1 => value1, key2 => value2...)
PHP array() Function

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and
" . $cars[2] . ".";
?>

I like Volvo, BMW and Toyota.


PHP count() Function

The count() function returns the number of elements in an array.

Syntax
count(array, mode)

array Required. Specifies the array


mode •Optional. Specifies the mode. Possible
values:0 - Default. Does not count all
elements of multidimensional arrays
•1 - Counts the array recursively
(counts all the elements of
multidimensional arrays)
print_r function
• The print_r() function prints the information about a variable in a more human-
readable way.
• Syntax
• print_r(variable, return);
• Parameter Values

• Return
variable Values Required. Specifies the variable to return information about

Return Value: If variable is integer, float, or string, the value itself will be printed. If variable is
array or object, this function returns keys and elements. If the return parameter is
set to TRUE, this function returns a string
• <?php
$a = array("red", "green", "blue");
print_r($a);

echo "<br>";

$b
= array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
print_r($b);
?> Array ( [0] => red [1] => green [2] => blue )
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
The print and print_r functions in PHP serve different purposes and
are used in different contexts.
print:
Usage:
print is primarily used for outputting strings and variables. It is a
language construct rather than a function, and it can take one
argument.
It doesn't return a value; it always returns 1.
$message = "Hello, World!";
print $message;
print_r:
Usage:
print_r is used for displaying detailed information about a variable,
especially arrays and objects. It is mainly used for debugging
purposes.
It can take only one argument.
$myArray = array('apple', 'banana', 'cherry');
print_r($myArray);

Key Differences:
Output:
print is used to output simple values, usually strings or variables.
print_r is used to output the structure of arrays and objects in a more
readable format.
Return Value:
print doesn't have a return value.
print_r also doesn't have a meaningful return value (it returns true),
but it is used for its side effect of printing the variable's structure.
Formatting:
print is straightforward and outputs the variable as is.
print_r provides a more structured and readable output for arrays and
objects, making it useful for debugging.
PHP String

• A PHP string is a sequence of characters i.e.


used to store and manipulate text.
• There are 2 ways to specify string in PHP.
• single quoted
• double quoted
Single Quoted PHP String
Double Quoted PHP String
PHP functions
• strtolower()
strtolower() Converts a string to
lowercase letters

<?php
echo strtolower("HELLO WORLD.");
?>
hello world
PHP functions
• strtoupper()

• Convert all characters to uppercase:

<?php
echo strtoupper("Hello WORLD!");
?>

HELLO WORLD
PHP functions
• lcfirst() - converts the first character
of a string to lowercase
• ucfirst() - converts the first character
of a string to uppercase
• ucwords() - converts the first
character of each word in a string to
uppercase
Php functions
• strtolower()
• strtoupper()
• strrev()
• Strlen()
• lcfirst()
• Ucwords()
Php form handling
PHP Post Form

• Post request is widely used to submit form


that have large amount of data such as file
upload, image upload, login form, registration
form etc.
• The data passed through post request is not
visible on the URL browser so it is secured. You
can send large amount of data through post
request.
PHP Include File

• PHP allows you to include file so that a page


content can be reused many times. There are
two ways to include file in PHP.
• include
• require
Advantage

• Code Reusability: By the help of include and


require construct, we can reuse HTML code or
PHP script in many PHP scripts.
PHP include example

• PHP include is used to include file on the basis


of given path. You may use relative or absolute
path of the file. Let's see a simple PHP include
example.
PHP include vs PHP require

• If file is missing or inclusion


fails, include allows the script to continue but
• require halts the script producing a fatal
E_COMPILE_ERROR level error.
PHP Functions

• PHP function is a piece of code that can be


reused many times.
• It can take input as argument list and return
value.
• There are thousands of built-in functions in
PHP.
Parameterized Function

• PHP Parameterized functions are the functions


with parameters. You can pass any number of
parameters inside a function. These passed
parameters act as variables inside your
function.
• They are specified inside the parentheses,
after the function name.
• The output depends upon the dynamic values
passed as the parameters into the function.
Php default arguments
Recursive function
PHP Superglobals

PHP provides an additional set of predefined arrays


containing variables from the web server the environment,
and user input. These new arrays are called superglobals.

• In PHP, superglobals are built-in associative arrays that


provide access to various global variables. These arrays
are available in all scopes and can be accessed from any
function, class, or file without the need for special
syntax or declarations. Superglobals are prefixed with a
dollar sign ($) and an underscore (_).
$GLOBALS

• Contains a reference to every variable which is currently


available within the global scope of the script. The keys of
this array are the names of the global variables.

$globalVariable = "This is a global variable.";

function exampleFunction() {
// Accessing a global variable using $GLOBALS
echo $GLOBALS['globalVariable'];
}
exampleFunction(); // Outputs: This is a global variable.
$_SERVER
• $_SERVER
• This is an array containing information such as
headers, paths, and script locations.
• The entries in this array are created by the
web server.
• There is no guarantee that every web server
will provide any of these.
That contains information about the server
environment and the current request. It provides
details about the server, such as script filenames,
server names, request methods, and more. The
elements in $_SERVER are populated by the web
server and are accessible from anywhere in your
PHP script.
$_GET

• An associative array of variables passed to the


current script via the HTTP GET method.
$_POST

• An associative array of variables passed to the


current script via the HTTP POST method.
$_REQUEST

• An associative array consisting of the contents


of $_GET, $_POST, and $_COOKIE.
$_PHP_SELF

• A string containing PHP script file name in


which it is called.
• $_SERVER['PHP_SELF']
• The filename of the currently executing script,
relative to the document root
• $_SERVER['SERVER_NAME']
• The name of the server host under which the
current script is executing. If the script is
running on a virtual host, this will be the value
defined for that virtual host.
Math functions
• PHP provides many predefined math
constants and functions that can be used to
perform mathematical operations.
Math functions in PHP
• abs() • Min()
• Ceil() • Max()
• Floor() • Pow()
• Round() • Sqrt()
• Fmod() • Rand()
Abs()
• The abs() function returns the absolute
(positive) value of a number.

• abs(number);

• number Required. Specifies a number. If the


number is of type float, the return type is also
float, otherwise it is integer
• The abs() function in PHP is identical to what
we call modulus in mathematics. The modulus
or absolute value of a negative number is
positive.
Example
• <?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
?>
Output
6.7
6.7
3
3
Ceil()
• The ceil() function rounds a number UP to the
nearest integer.

• ceil(number);

• number Required. Specifies the value to


round up
Example
• <?php
echo(ceil(0.60) . "<br>");
echo(ceil(0.40) . "<br>");
echo(ceil(5) . "<br>");
echo(ceil(5.1) . "<br>");
echo(ceil(-5.1) . "<br>");
echo(ceil(-5.9));
?>
Output
1
1
5
6
-5
-5
Floor()
• The floor() function rounds a number DOWN
to the nearest integer.

• floor(number);

• number Required. Specifies the value to


round down
Example
• <?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
echo(floor(5.1) . "<br>");
echo(floor(-5.1) . "<br>");
echo(floor(-5.9));
?>
Output
0
0
5
5
-6
-6
Round()
• The round() function rounds a floating-point
number.

• round(number,precision,mode);

• number Required. Specifies the value to


round precision
• Optional. Specifies the number of decimal
digits to round to. Default is 0
• mode Optional. Specifies a constant to specify the
rounding mode: PHP_ROUND_HALF_UP - Default.
Rounds number up to precision decimal, when it is
half way there. Rounds 1.5 to 2 and -1.5 to -2
• PHP_ROUND_HALF_DOWN - Round number down
to precision decimal places, when it is half way
there. Rounds 1.5 to 1 and -1.5 to -1
• PHP_ROUND_HALF_EVEN - Round number to
precision decimal places towards the next even
value
• PHP_ROUND_HALF_ODD - Round number to
precision decimal places towards the next odd value
Example 1
• <?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
Output
1
1
0
-4
-5
Example 2
• <?php
echo(round(4.96754,2) . "<br>");
echo(round(7.045,2) . "<br>");
echo(round(7.055,2));
?>

• 4.97
7.05
7.06
Example 3

• <?php
echo(round(1.5,0,PHP_ROUND_HALF_UP) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "<br>");

echo(round(1.5,0,PHP_ROUND_HALF_DOWN). "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_DOWN).
"<br>");

echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");

echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_ODD));
Example
2
-2
1
-1
2
-2
1
-1
Fmod()
• The fmod() function returns the remainder
(modulo) of x/y.

• fmod(x,y);
Example
• <?php
$x = 7;
$y = 2;
$result = fmod($x,$y);
echo $result;
?>
Output
1
Min ()
• The min() function returns the lowest value in
an array, or the lowest value of several
specified values.

• min(array_values);

or

min(value1,value2,...);
Example
• <?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>
• 2
14
4
12
Max()
• The max() function returns the highest value in an
array, or the highest value of several specified
values.

• max(array_values);

or

max(value1,value2,...);
Example
• <html>
<body>

<?php
echo(max(2,4,6,8,10) . "<br>");
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>

</body>
</html>
Pow()
• The pow() function returns x raised to the
power of y.

• pow(x,y);

• x Required. Specifies the base to use


• y Required. Specifies the exponent
Example
<html>
<body>
<?php
echo(pow(2,4) . "<br>"); //16
echo(pow(-2,4) . "<br>");//16
echo(pow(-2,-4) . "<br>");//0.0625
?>
</body>
</html>
Sqrt()
• The sqrt() function returns the square root of
a number.

• sqrt(number);

• number Required. Specifies a number


Example
<?php
echo(sqrt(0) . "<br>"); // 0
echo(sqrt(1) . "<br>"); // 1
echo(sqrt(9) . "<br>"); // 3
echo(sqrt(0.64) . "<br>"); // 0.8
?>
Rand()
• The rand() function generates a random
integer.

• rand();

or

rand(min,max);
Example
• <?php
echo(rand() . "<br>"); // 31123
echo(rand() . "<br>"); // 24494
echo(rand(10,100)); // 49
?>
Chr()
• The chr() function returns a character from
the specified ASCII value.
• The ASCII value can be specified in decimal,
octal, or hex values. Octal values are defined
by a leading 0, while hex values are defined by
a leading 0x.
Example
Syntax
• chr(ascii)

• <?php
echo chr(52) . "<br>"; // Decimal value 4
echo chr(052) . "<br>"; // Octal value *
echo chr(0x52) . "<br>"; // Hex value R
?>
Ord()
• The ord() function returns the ASCII value of
the first character of a string.
• Syntax:ord(string)

• <?php
echo ord("h")."<br>"; //104
echo ord("hello")."<br>"; //104
?>
Trim()
• ltrim() - function removes whitespace or
other predefined characters from the left side
of a string.
• rtrim() - Removes whitespace or other
predefined characters from the right side of a
string
• trim() - Removes whitespace or other
predefined characters from both sides of a
string
• <?php
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
?>
• Hello World!
• World!
• <?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

• llo worl
Die()
• The die() function prints a message and exits
the current script.
• This function is an alias of the exit() function.

• Syntax
die(message)
• <?php
$site = "https://www.google.com/";
fopen($site,"r")
or die("Unable to connect to $site");
?>
cookies
In PHP, cookies are small pieces of data that can be stored on the user's
computer. They are often used to persistently store information between page
requests. Here's a basic overview of how to work with cookies in PHP

Setting Cookies:
You can set a cookie using the setcookie() function. The basic syntax is as follows:

setcookie(name, value, expire, path, domain, secure, httponly);

name: The name of the cookie.


value: The value of the cookie.
expire: The expiration time of the cookie (in seconds since the Unix Epoch). If set
to 0, the cookie will expire at the end of the session.
path: The path on the server where the cookie is available.
domain: The domain for which the cookie is available.
secure: If set to true, the cookie will only be sent over secure connections
(HTTPS).
httponly: If set to true, the cookie will only be accessible through the HTTP
protocol.
Here's an example:

<?php
// Set a cookie named "user" with the value "John Doe" that expires in one hour
setcookie("user", "John Doe", time() + 3600, "/");
?>

Retrieving Cookies:

You can retrieve the value of a cookie using the $_COOKIE superglobal array. For
example:
<?php
// Check if the "user" cookie is set
if (isset($_COOKIE["user"])) {
// Retrieve and print the value of the "user" cookie
echo "Welcome " . $_COOKIE["user"] . "!";
} else {
echo "Cookie not set!";
}
?>
Deleting Cookies:
To delete a cookie, you can set its expiration time to a past
date. For example:

<?php
// Expire the "user" cookie by setting its expiration time to the
past
setcookie("user", "", time() - 3600, "/");
?>
sessions
• An alternative way to make data accessible
across the various pages of an entire website
is to use a PHP Session.
• A session creates a file in a temporary
directory on the server where registered
session variables and their values are stored.
• This data will be available to all pages on the
site during that visit.

You might also like