Unit II (1)
Unit II (1)
Control Structures
Conditional statements
PHP if else statement is used to test condition.
There are various ways to use if statement in
PHP.
Often when you write code, you want the same block of code to run over
and over again a certain number of times.
Loops are used to execute the same block of code again and again,
as long as a certain condition is true.
The for loop is used when you know in advance how many times the script should
run.
Syntax
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
<?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
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
");
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");
Syntax
<?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:
<?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
$x = 0;
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
The action attribute specifies where to send the form-data when a form is
submitted.
<form action="URL">
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
• 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
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and
" . $cars[2] . ".";
?>
Syntax
count(array, mode)
• 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
<?php
echo strtolower("HELLO WORLD.");
?>
hello world
PHP functions
• strtoupper()
<?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
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
• abs(number);
• ceil(number);
• floor(number);
• round(number,precision,mode);
• 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);
• sqrt(number);
• 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:
<?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.