You are on page 1of 82

Program Title:- Computer Engineering

Sem/Year:- 6th (I Scheme)


Course Title:- Web Based Application development with PHP
Course Abbreviation:- WBP Course Code:- 22619
Level of understanding the subject :- Easy & Medium

Prerequis Knowledge about Web Page Designing and Proficiency in programming


ites language and analytical skills.
Learning Students will get the knowledge of web based
Objective Knowledge
application development.
(What
Students will understand the process of Server
will my Understanding
installation and use of Scripting language.
students
Students will perform various operation on
KNOW Application
Arrays and Graphics.
by the
end of the Students will learn to analyse programming
Analysis
subject?) constructs and apply appropriate one.

Student will be able to design form and validate


Evaluation
controls.
Student will be able to create database and
Create
perform database operations.
Teaching Scheme

Teaching
Theory Practical
Scheme
Credit
(L+T+P) Paper ESE PA TOTAL ESE PA TOTAL
L T P
hrs. Max Min Max Min Max Min Max Min Max Min Max Min

3 - 2 5 3 70 28 30* 0 100 40 25@ 10 25 10 50 20

Rationale :- To inculcate web based application development skills in students using


server side scripting.
Competency: Develop simple web based application using PHP Language.

Course Outcomes:
a. Develop Program using Control Statements.
b. Perform operations based on arrays and graphics.
c. Develop Program by applying various object oriented concepts.
d. Use form controls with validation to collect user’s input.
e. Perform database operations in PHP
Index
S.N. Description TH No. of
Understanding Marks Hrs Pr
Level
Units 70 48 16
1. Expressions & Control Statements in PHP Easy 12 06 3
2. Arrays, Functions & Graphics Medium 16 10 4
3. Apply Object Oriented Concepts in PHP Medium 16 12 2
1 4. Creating & Validating Forms Medium 12 12 5
5. Database Operations Medium 14 08 2
2 Assignments 5
50
3 Practice questions-Unit Tests
Questions
5Q-2M ,5Q-4M

4 List of Micro-project 10 ----- -----

5 Question papers & Models answer solution 4 ----- -----


1. Expressions & Control Statements in PHP
LOs Learning Outcomes/Unit Outcomes

1a Write Simple PHP Program to solve the


given expression.
1b
Use relevant decision making control
statements to solve the given problem.
1c
Solve iterative problem using relevant
loop statement.
PHP

• PHP started out as a small open source project that evolved as more and more
people found out how useful it was.
• Rasmus Lerdorf unleashed the first version of PHP(Personal Home Page) way
back in 1994.
• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
• PHP is a server side scripting language that is embedded in HTML.
• It is used to manage dynamic content, databases, session tracking, even build entire
e-commerce sites.
• It is integrated with a number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
Common uses of PHP

1. It handles dynamic content, database as well as session tracking for the website.
2. You can create sessions in PHP.
3. It can access cookies variable and also set cookies.
4. It helps to encrypt the data and apply validation.
5. PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
6. Using PHP language, you can control the user to access some pages of your website.
7. As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
8. PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration
form.
Performance:
PHP script is executed much faster than those scripts which are written in other languages such as JSP
and ASP. PHP uses its own memory, so the server workload and loading time is automatically reduced,
which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of PHP
according to your requirement without paying any cost. All its components are free to download and
use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g., E_ERROR, E_WARNING,
E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of execution based on
the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and malicious
attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work in a few lines of code. It has
maximum control over the websites like you can make changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online help, and FAQs. Learning PHP
from the communities is one of the significant benefits.
History of PHP
History of PHP

The Origin
• Rasmus Lerdorf started developing PHP in 1994.
• A lot of CGI programs were written by him which were used for maintenance of his
personal website.
• He modified these programs to make them work with web forms and to interact with
databases. The implementation of this modification was termed as “Personal Home
Page/Forms Interpreter” (PHP/FI).
• The first version of PHP/FI was made available to the world by Lerdorf in June 1995 Rasmus
for Bug Reporting and Code Improvement.
• Features like Form Handling, Variables similar to Perl and HTML embedding were
present in this first version.
PHP 2
• in late 1997 after a lot of beta testing. As PHP was developed organically, there was a
lot of inconsistency in function names and parameter order.
PHP 3
Zeev
• The parser was rewritten in 1997 by Zeev Suraski and Andi Gutmans which led to the
formation of PHP 3 base.
• After changing its name to PHP which meant Hypertext Preprocessor, its public testing
was started. PHP 3 was officially launched in June 1998.
• A fresh rewriting of the PHP core started by Zeev and Andi, In 1999, they produced the
Zend Engine and also established Zend Technologies in Israel.
PHP 4
• Zend Engine 1.0 powered PHP 4 was released in May 2000.
• PHP 4 reached its version 4.4.9 in August 2008. Andi
PHP 5
• Powered by Zend Engine 2, PHP 5 was launched in July 2004.
• It had features like PDO Extension, improved support for OOPS and many other
performance improvements. PHP was able to become the only stable version by 2008.
• A consortium of PHP developers started the GoPHP5 initiative which promoted the
transition from PHP 4 to PHP 5.

PHP 6 (Never Released)


• Due to the lack of support for native Unicode, PHP received mixed reviews.
• A project was initiated in 2005 to introduce native Unicode support through PHP.
• This project was headed by Andrei Zmievski. As it would require major changes, it was
decided to launch this update as a new version naming it PHP 6.0.
• But the shortage of developers who understood the necessary changes resulted in the delay
of the project. Considering this delay, PHP 5.3 was released in 2009 which included many
features from the PHP 6 project. The project development was stopped in March 2010.

PHP 7
• Another major version of PHP was developed in 2014 and 2015. This version was termed as
PHP 7 which caused some confusion as PHP 6 was never released. PHP 7 was also known
as PHP next generation(phpng). The aim of this version was to optimize the performance by
refactoring the Zend Engine and preserving the near-complete language compatibility.
• In July 2014, benchmarks showed a nearly 100% increase in performance.
Advantages of PHP
Advantages of PHP

1. It is open source, free from cost. It can be downloaded anywhere and is readily available for
events or web applications.
2. It is platform-independent. PHP-based applications can run on any OS like UNIX, Linux,
Windows, etc.
3. Applications can easily be loaded which are based on PHP and connected to the database. It’s
mainly used due to its faster rate of loading over slow internet speed than other programming
language.
4. It has less learning curve because it is simple and straightforward to use. Someone familiar with
C programming can easily work on PHP.
5. It is more stable for a few years with the assistance of providing continuous support to various
versions.
6. It helps in reusing an equivalent code and not got have to write lengthy code and sophisticated
structure for events of web applications.
7. It helps in managing code easily.
8. It has powerful library support to use various function modules for data representation.
9. PHP’s built-in database connection modules help in connecting databases easily reducing trouble
and time for the development of web applications and content-based sites.
10. The popularity of PHP gave rise to various communities of developers, a fraction of which may
be potential candidates for hire.
11. Flexibility makes PHP ready to effectively combine with many other programming languages in
order that the software package could use foremost effective technology for every particular
feature.
Drawbacks of PHP

1. It is not that secure due to its open-source, because the ASCII text file is often easily available.
2. It is not suitable for giant content-based web applications.
3. It has a weak type, which can cause incorrect data and knowledge to users.
4. PHP frameworks got to learn to use PHP built-in functionalities to avoid writing additional code.
5. Using more features of PHP framework and tools cause poor performance of online applications.
6. PHP doesn’t allow change or modification in the core behavior of online applications.
7. The PHP frameworks aren’t equivalent in behavior so does their performance and features.
8. While PHP may be a powerful tool supported by an outsized community and plentiful reference
documentation, there are easier programming languages for web apps.
9. It is widely believed by the developers that PHP features a poor quality of handling errors. PHP
lacks debugging tools, which are needed to look for errors and warnings. PHP has less number of
debugging tools in comparison to other programming languages.
10. It’s highly tough to manage because it’s not competent modular. It already imitates the features of
the Java language.
Character set of PHP

Alphabets : a---z / A----Z

Numbers : 0--- 9

Symbols: + , - , ( ,{ , ; , ], <, =,etc

Token: Any word formed from above character set ,having meaning is

known as token.
Types of token:
1. Keywords: reserved words of language. E.g. int, break,for,while, float,echo ,etc

2. Identifiers : name given to variable, function,class.

E.g. int a, class abc, void show() - here a,abc and show are the identifiers

3. Operators: symbols that performs a task. E.g. + , < ,= , etc

4. Constants: are variables who value do not changes throught the program

In PHP, constants are defined using define( ) function

5. Special Symbols: symbols having meaning. E.g.

{ , } for blocks, [, ] –for array, ; -foe end of statement


PHP - Syntax Overview
• Canonical PHP tags

The most universally effective PHP tag style is −

<?php...?>

•Short or short-open tags look like this −

<?...?>

•ASP-style tags
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks.
ASP-style tags look like this −

<%...%>

•HTML script tags

<script language = "PHP">...</script>


•Commenting PHP Code
Single-line comments

<?
# This is a comment, and # This is the second line of the comment
// This is a comment too. Each style comments only print "An example with single line
comments";
?>

Multi-lines Comments

<? /* This is a comment with multiline Author : Mohammad Mohtashim Purpose: Multiline
Comments Demo Subject: PHP */
print "An example with multi line comments";
?>

•PHP is whitespace insensitive


PHP whitespace insensitive means that it almost never matters how many whitespace characters you
have in a row
•PHP is case sensitive.
•Statements are expressions terminated by semicolons
•Expressions are combinations of tokens.
The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().
<?php
echo "PHP is Fun!";
echo "Hello world!";
?>
The following example shows how to output text and variables with the echo
statement:

<?php
$txt1 = "Learn PHP";
$txt2 = “welcome";
$x = 5;
$y = 4;
echo " $txt1 ";
echo "Study PHP at $txt2";
echo $x + $y;
?>
The PHP print Statement

The print statement can be used with or without parentheses: print or print().
Example :
<?php
print "PHP is Fun!";
print "Hello world!";
print "I'm about to learn PHP!";
?>
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "Welcome";
$x = 5;
$y = 4;
print "$txt1";
print "Study PHP at $txt2 ";
print $x + $y;
?>
Reading input from user

<?php

$a = readline(“Enter a string: “);

echo $a;
?>
<?php

$a = (int)readline('Enter an integer: ');

$b = (float)readline('Enter a floating point number: ');

echo “values are : $a and $b”;


?>
Variable Naming
Rules for naming a variable is −
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
•There is no size limit for variables.
Types of variable /Variable Scope/Lifetime of variable
Scope can be defined as the range of availability a variable has to the program in which it
is declared. PHP variables can be one of four scope types −
• Local variables
• Function parameters
• Global variables
• Static variables
.
Local Variables
A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any
assignment outside of that function will be considered to be an entirely different variable from the one
contained in the function −
<?php
$x = 4;
function assignx()
{ $x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. “;
?>
This will produce the following result −
$x inside function is 0.
$x outside of function is 4.
•Function Parameters :

Function parameters are declared after the function name and inside parentheses.
They are declared much like a typical variable would be −

<?php

// multiply a value by 10 and return it to the caller

function multiply ($value)


{ $value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>

This will produce the following result −


Return value is 100
Global Variables:

• can be accessed in any part of the program.


• by placing the keyword GLOBAL in front of the variable that should be
recognized as global.
• Placing this keyword in front of an already existing variable tells PHP to use the
variable having GLOBAL name.

Consider an example −
<?php
$a = 15;
function addit()
{ GLOBAL $a;
$a++;
print “a is $a";
}
addit();
?>
This will produce the following result − a is 16
Static Variables:
• static variables means only one copy of that variable exists and value is common

<?php

function keep_track()
{
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result −
1
2
3
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
• constants are automatically global across the entire script.

To create a constant, use the define() function.


Syntax:

define(name, value, case-insensitive)

Parameters:
• 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. Note: Defining case-insensitive constants was deprecated in PHP 7.3.
PHP 8.0 accepts only false, the value true will produce a warning.
Example :

Create a constant with a case-sensitive name:

<?php

define("WBP", "Welcome to PHP!");

echo WBP;

?>

Output:
Welcome to PHP!
PHP Operators:

Operators are used to perform operations on variables


and values.

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional operators
• PHP Arithmetic Operators:

The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction,
multiplication etc.

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


Example: Exponentiation

<?php
$x=readline(“enter x: ”);
$y=readline(“enter y: ”);
echo $x ** $y;
?>
Output:
enter x: 10
enter y: 3
1000
• PHP Assignment Operators:
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=".
It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as... Description


The left operand gets set to the value of the
x=y x=y
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
Example: *=

<?php
$x=readline(“enter x: ”);
$x *=6; Similar to $x =$x*6;

echo $x;
?>
Output:
enter x: 5
30
• PHP Comparison Operators:
The PHP comparison operators are used to compare two values (number or string).

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to $y
Returns true if $x is equal to $y, and they are of the
=== Identical $x === $y
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
Returns true if $x is not equal to $y, or they are not of
!== Not identical $x !== $y
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
>= $x >= $y Returns true if $x is greater than or equal to $y
equal to
Less than or equal
<= $x <= $y Returns true if $x is less than or equal to $y
to
Returns an integer less than, equal to, or greater than
<=> Spaceship $x <=> $y zero, depending on if $x is less than, equal to, or
greater than $y. Introduced in PHP 7.
Example: Identical ===

<?php
$x=100;
$y=“100”;
var_dump($x===$y);
?>
Output:
bool(false)

Var_dump() is function which displays on screen the type and


value of variable or expression given in brackets.
Example: Spaceship operator < = >

<?php Output:
$x=10;
$y=15;
-1
echo ($x < = >$y);
0
1
$x=10;
$y=10; At first echo ,returns -1 bcz 10>15
echo ($x < = >$y);
At second echo ,returns 0 bcz 10=10
$x=15;
$y=10;
echo ($x < = >$y); At third echo ,returns 1 bcz 15>10

?>
• PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one


Example: Pre-increment and post increment

<?php
$x=10;
echo (++$x);
Output:

11
$y=6; 6
echo ($y++);

?>
• PHP Logical Operators :

The PHP logical operators are used to combine conditional statements.

Operato
Name Example Result
r
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

True if either $x or $y is true, but not


xor Xor $x xor $y
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


Example: &&

<?php
$x=10;
$y=20;
Output:
if($x==10 && $y==20)
done
echo “done”;
?>
Example: xor

<?php
$x=10;
$y=30;
Output:
if($x==10 xor $y==20)
done
echo “done”;
?>
• PHP String Operators :

PHP has two operators that are specially designed for strings .

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

Concatenation
.= $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
Example: concatenation

<?php Output:

$x=“Welcome to“; Welcome to PHP World


$y=“PHP World”;
echo $x.$y;
?>
Example: append

<?php Output:

$x=“Welcome to“; Welcome to PHP World


$y=“PHP World”;
$x.=$y;
echo $x;
?>
• PHP Array Operators
The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

Returns true if $x and $y have the same


== Equality $x == $y
key/value pairs

Returns true if $x and $y have the same


=== Identity $x === $y key/value pairs in the same order and of
the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y


Example: Creating array in PHP

<?php
$cars=array(‘harrier’ , ’range rover’, ’echosports’);
echo $cars;
?>

<?php
$cars=array(‘harrier’ , ’range rover’, ’echosports’);
var_dump($cars);
Output:
?>
array(3) {[0]= > string(7) “harrier” {[1]= > string(17)
“range rover” {[2]= > string(10) “echosports”
Example: Array operators

<?php
$cars=array(‘harrier’ , ’range rover’, ’echosports’);
$bikes=array(‘jupiter’ ,’activa’);
$u=$cars+$bikes;
echo $u;
echo ($cars==$bikes);
?>
• PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result

Returns the value of $x.


The value of $x is expr2 if expr1 =
?: Ternary $x = expr1 ? expr2 : expr3 TRUE.
The value of $x is expr3 if expr1 =
FALSE
Returns the value of $x.
The value of $x
is expr1 if expr1 exists, and is not
?? Null coalescing $x = expr1 ?? expr2 NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
Introduced in PHP 7
Example: Ternery operators

<?php
$a=10;
$b=15;
$max=$a>$b?$a:$b;
echo (“largest no :$max” );
?>

Output:
largest no : 15
Null coalescing
Example:

<?php
$a=10;
echo ($a) ?? “NULL”;
?>

It will return values if its not null otherwise it will


return NULL
PHP Decision Making Statements

- PHP allows us to perform actions based on some type of conditions that


may be logical or comparative.
- Based on the result of these conditions i.e., either TRUE or FALSE, an
action would be performed as asked by the user.

• if statement
• if…else statement
• if…elseif…else statement (else if ladder)
• switch statement
• break statement
• continue statement
1.if Statement:
- This statement allows us to set a condition.
- On being TRUE, the following block of code enclosed within the if clause will be
executed.

Syntax :
if (condition)
{ // if TRUE then execute this code
}
Example:
<?php

$x = 10;
if ($x > 0)
{
echo "The number is positive";
}
?>
Output:
The number is positive
2. if…else Statement:
If a condition is TRUE then if block gets executed, otherwise else block gets executed.
Syntax:
if (condition)
{ // if TRUE then execute this code
}
else
{ // if FALSE then execute this code
}
Example:
<?php
$x = -10;
if ($x > 0)
{ echo "The number is positive";
}
else
{ echo "The number is negative";
}
?>
Output:
The number is negative
3.if…elseif…else Statement: Example:

This allows us to use multiple if…else <?php


statements. We use this when there are $x = "August";
multiple conditions of TRUE cases. if ($x == "January")
Syntax: {
if (condition 1) { echo "Happy Republic Day";
// if TRUE then execute this code }
} elseif ($x == "August")
elseif (condition 2){ {
// if TRUE then execute this code echo "Happy Independence Day!!!";
} }
| else
| {
elseif (condition n){ echo "Nothing to show";
// if TRUE then execute this code }
} ?>
else { Output:
// if FALSE then execute this code Happy Independence Day!!!
}
Syntax:
4.switch Statement:
• it has various cases to which it matches switch(n)
{
the condition and appropriately executes case statement1:
a particular case block. code to be executed if n==statement1;
break;
• It first evaluates an expression and then case statement2:
compares with the values of each case. code to be executed if n==statement2;
break;
case statement3:
1.The break statement is used to stop the code to be executed if n==statement3;
break;
automatic control flow into the next cases case statement4:
and exit from the switch case. code to be executed if n==statement4;
break;
2.The default statement contains the code ......
that would execute if none of the cases default:
code to be executed if n != any case;
match. }
<?php

$num=20;

switch($num)
{
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20
or 30");
}
?>
PHP Loop Control Structures:
Loops in PHP are used to execute the same block of code a specified number of
times.
PHP supports following four loop types.

•for − loops through a block of code a specified number of times.

•while − loops through a block of code if and as long as a specified condition


is true.
•do...while − loops through a block of code once, and then repeats the loop as
long as a special condition is true.
•foreach − loops through a block of code for each element in an array.
for loop statement
- used when you know how many times you want to
execute a
statement or a block of statements.
Syntax:
for (initialization; condition; increment)
{
code to be executed;
}
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ )
{ $a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
2. while loop
-will execute a block of code if and as long as a test
expression is true.
-is an entry controlled loop; before executing code, test
condition is checked.

Syntax :
Initialization of counter;
while (condition)
{ code to be executed;
increment/decrement of counter;
}
Statement n;
Example:

<?php
$i = 0;
while( $i < =10)
{
echo “Number: $i”;
$i++;
}
echo (“Bye" );
?>
3. do...while loop statement

- Is an exit controlled loop, condition is checked after executing a


block.
-will execute a block of code at least once even if condition is
false

Syntax:

Initialization of counter;
do {
code to be executed;
increment/decrement of counter;
}while (condition);
Statement n;
Example:

<?php
$i = 0;
do
{ $i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
4. foreach loop statement
-is used to loop through arrays.
-For each pass the value of the current array
element is assigned to $value
-and the array pointer is moved by one and in the
next pass next element will be processed.
Syntax:
foreach (array as value)
{
code to be executed;
}
Example:

<?php
$ar= array( 1, 2, 3, 4, 5);
foreach( $ar as $v )
{ echo "Value is $v";
}
?>
break statement
-break keyword is used to terminate the execution of a
loop prematurely.
-is situated inside the statement block.
-After coming out of a loop immediate statement to the
loop will be executed.

<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )
break;
}
echo ("Loop stopped at i = $i" );
?>
continue statement
-continue keyword is used to halt the current iteration of
a loop
-it does not terminate the loop.
-For the pass encountering continue statement, rest of the
loop code is skipped and next pass starts

<?php
$ar = array( 1, 2, 3, 4, 5);
foreach( $ar as $v )
{
if( $v = = 3 )
continue;
echo "Value is $v";
}
?>
Programs

Simple display a msg

<?php

echo "Welcome";

print " GGSP";

?>
Programs

Find Even Odd :


<?php
$a=20;
if($a%2==0)
{
print "$a is Even No.";
}
else
{
print "$a is Odd No.";
}
?>
Programs

Addition

<?php

$a=20;

$b=30;

$c=$a+$b;

print "Addition of 2 No. is $c";

?>
Largest of 2 Number
<?php
$a=20;
$b=10;
if($a > $b)
{
print "a is Larger No.";
}
else
{
print "b is Larger No.";
}
?>
Print Even Number 1 to 20 using While Loop

<?php
$i=2;
while($i<=20)
{
echo "$i \n";
$i=$i+2;
}
?>
Print odd Number between 1 to 20 using do--While Loop

<?php
$i=1;
do
{
echo "$i \n";
$i=$i+2;
} while($i<=20);
?>
Print sum of Even Numbers from 1 to 20
<?php
$i=2;
$sum=0;
while($i<=20)
{ $sum=$sum+$i;
$i=$i+2;
}
echo “Sum is : $sum \n";
?>
Switch Case program for Arithmetic Operation
<?php
$a =readline('Enter Number 1:'); case '*':
$b =readline('Enter Number 2:'); $c=$a*$b;
$c; print "$c \n";
$choice =readline("Enter Your break;
Choice'+,-,*,/' :-"); case '/':
switch($choice) $c=$a/$b;
{ print "$c \n";
case '+': break;
$c=$a+$b; default:
print "$c \n"; print "Invalid Operation";
break; break;
case '-': }
$c=$a-$b; ?>
print "$c \n";
break;
Factorial program in PHP using for loop

<?php
$n=readline(“enter a number”);
$fact=1;
for($i=1;$i<=$n;$i++)
{
$fact=$fact*$i;
}
echo "factorial of $n is: $fact";
?>
Program for reversing of number:
function rev($num)
{
$r = 0;
while($num > 1)
{
$r = $r * 10 + $num % 10;
$num = (int)$num / 10;
}
return $r;
}

$num = 456213;
echo "Original number is :".$num;
echo "\r\n";
echo "Reverse of no. is ", rev($num);
?>
Print the first 12 numbers of a Fibonacci series.
<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "Fibonacci series for first 12 numbers:";
echo “$n1”;
echo “$n2 ' ';
while ($num < 10 )
{ $n3 = $n2 + $n1;
echo $n3;
$n1 = $n2;
$n2 = $n3;
$num ++;
?>
THANK YOU

You might also like