Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views28 pages

AWD - Unit-1 Introduction To PHP

Uploaded by

devanshubhatt18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

AWD - Unit-1 Introduction To PHP

Uploaded by

devanshubhatt18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

School of Diploma Studies

Faculty of Engineering and Technology

Computer Engineering Department

Semester - 5

Advance Web Development


(21DCECC503)

Unit – 1 Introduction to PHP

Ms. Bhumika S. Zalavadia


Head of Department

Yogidham Gurukul, Kalawad Road, Rajkot - 360005


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

Q – 1 What is website? Explain its types?


 Website is a collection of related web pages that may contain text, images, audio and video.
 The first page of a website is called home page or index page.
 Each website has specific internet address (URL) that you need to enter in your browser to
access a website.
 Website is hosted on one or more servers and can be accessed by visiting its homepage using a
computer network. A website is managed by its owner that can be an individual, company or an
organization.
Types of Website
1. Static Website
2. Dynamic Website
1. Static Website
 Static website is the basic type of website that is easy to create.
 You don't need the knowledge of web programming and database design to create a static
website. Its web pages are coded in HTML.
 The codes are fixed for each page so the information contained in the page does not change and
it looks like a printed page.
2. Dynamic Website
 Dynamic website is a collection of dynamic web pages whose content changes dynamically. It
accesses content from a database or Content Management System (CMS). Therefore, when you
alter or update the content of the database, the content of the website is also updated.
 It uses client-side scripting or server-side scripting, or both to generate dynamic content.
 Client side scripting generates content at the client computer on the basis of user input. The
web browser downloads the web page from the server and processes the code within the page
to render information to the user.
 In server side scripting, the software runs on the server and processing is completed in the
server then plain pages are sent to the user.

Static Website Dynamic Website

Prebuilt content is same every time the page is Content is generated quickly and changes
loaded. regularly.
It uses the server-side languages such
It uses the HTML code for developing a website. as PHP, Servlet, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for every It may generate different HTML for each of
request. the request.

Prepared By: Bhumika S. Zalavadia Page 1


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

The content is only changed when someone The page contains server-side code which
publishes and updates the file (sends it to the web allows the server to generate the unique
server). content when the page is loaded.

Content Management System (CMS) is the


Flexibility is the main advantage of static website.
main advantage of dynamic website.

Q – 2 What is PHP? Explain brief history of PHP.


 PHP is a server side scripting language which is used in web based applications. The full form of
PHP is “Hypertext Preprocessor”. Its original name was “Personal Home Page”.
 Rasmus Lerdorf software engineer who is Apache team member is the creator and original
driving force behind PHP/FI (Personal Home Page/Forms Interpreter"). The first version PHP 1
was released in June1995.
Release History

Version Month of Release Version Month of Release


PHP 1 June 1995 PHP 5.3 June 2009
PHP 2 November 1997 PHP 5.4 March 2012
PHP 3 June 1998 PHP 5.5 June 2013
PHP 4 May 2000 PHP 5.6 August 2014
PHP 4.1 December 2001 PHP 7 December 2015
PHP 4.2 April 2002 PHP 7.1 December 2016
PHP 4.3 December 2002 PHP 7.2 November 2017
PHP 5 July 2004 PHP 7.3 December 2018
PHP 5.1 November 2005 PHP 7.4 November 2019
PHP 5.2 November 2006 PHP 8 November 2020
PHP 8.5 November 2023

Q – 3 Explain features (advantages) of PHP.


 Open Source: PHP is open source software. We do not need to purchase it from market. Thus it
costs nothing. Open source software can be modified by any user all over the world.

Prepared By: Bhumika S. Zalavadia Page 2


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 Ease of Use: PHP is easy to learn. Syntax of PHP is somewhat like C language. A lot of Ready-
made PHP scripts are freely available in market so, you can use them in your project or get
some help from them.
 HTML Support: PHP can be embedded within HTML. PHP allows us to interact with HTML
page dynamically. We can also embed HTML code within PHP script.

 Database Support: PHP supports many databases like MySQL, Oracle, Sybase, Generic ODBC
etc. We can create database in MySQL and connect it with PHP script to perform database
operations like insert, update or delete.
 Cross-platform Compatibility: PHP and MySQL run on every popular flavor of Unix and
windows. A huge percentage of the world’s HTTP servers run on one of these two categories of
operating system.
 PHP is compatible with the three leading Web Servers
o Apache HTTP Server for Unix and Windows
o MS Internet Information Server(IIS)
o Netscape Enterprise Server.
 Stability: The word stable means two different things in this context:
o The server doesn’t need to be rebooted often
o PHP doesn’t change drastically and incompatibly from release to release.

Q – 4 What do you mean by Open Source Software (OSS)?


 There is an international community which develops the software free to download and use.
This software is known as Open Source Software.
 Open source software can be used or modified by anyone.
 PHP, MySQL, Apache etc. are open source software.
 The idea of open source software promotes the software reliability and quality by supporting
other’s review.

Q – 5 What is web server? What is Apache web server?


 Web server is software which allows us to host the web pages. The local web server lets you to

Prepared By: Bhumika S. Zalavadia Page 3


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

write and test programs running from your local computer exactly the same way they will be
seen on internet.
 Apache is the most popular open source web server which runs on Windows, Linux and many
other OS.
 The scripts written in PHP can be run by Apache which can contain text, images, MP3 or
graphics data.
 Apache is stable and easy to use once it is installed.
 Apache also supports a huge range of modules like GD Library and other for handling security.

Q – 6 Explain the relationship between Apache, MySQL and PHP (AMP module).
 AMP stands for Apache web server, MySQL database and PHP language.
 All these three are open source. They don’t need to be purchased from market. They are freely
available on internet.
 PHP is used to create web pages. MySQL is used to create database for the storage of website
data and Apache is used to run PHP pages.
 The combination of these there allows us to create dynamic interactive websites. It can be
installed on Windows (WAMP), Linux platform (LAMP) or XAMPP for both Windows and Linux
platforms.
 Once you install the PHP and Apache server, you should start the Apache service and then type
following in web browser.
http://10.9.1.35/……. OR http://localhost/webpage.php

Where 10.9.1.35 is the IP of local computer. Localhost is your local server means the Apache
web server installed in your computer.

Q – 7 What is MySQL and phpmyadmin?


MySQL
 MySQL is a relational database server. It supports standard SQL (Structured Query Language).

 It is open source and free to download.


 It is used on number of platforms like Windows and Linux.

Prepared By: Bhumika S. Zalavadia Page 4


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 It is best suited with PHP.


phpmyadmin
 phpMyAdmin is a free web application that provides a convenient GUI for working with the
MySQL database management system.
 It is written in PHP.
 Frequently used operations like managing databases, tables, columns, relations, indexes, users,
permissions, etc. can be performed in it
 It is the most popular MySQL administration tool that is used by millions of users worldwide.

Q – 8 Explain the general structure and syntax of PHP with example. How does PHP
work?
 Any PHP file generally may contain some HTML tags, CSS, JavaScript and PHP code.

 You can use any PHP editor like Notepad or Dreamweaver to write PHP code. The file must be
saved with .php extension. If the file is saved with .html extension then the php code will not be
executed.
 There are different PHP tags which can be used to write PHP script (code). They are followings.
1. Standard PHP Tag
<?php
echo "Hello Friends";
?>
2. Short Tag
<?
echo "Hello Friends";
?>
 Generally the standard tag is used in routine PHP programming.
 Two statements are used to display the text on PHP page: echo and print.
 PHP is server side scripting language that means script code is processed on the web server like
Apache or IIS rather than on client side.

Prepared By: Bhumika S. Zalavadia Page 5


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 Semicolon: Each code line must ends with semicolon which is the separator used to separate
one instruction from next instruction.
 White Space: White space is ignored between PHP statements.
 Case Sensitivity: PHP is case sensitive scripting language.

 Comments: In PHP // is used for single line comment and /* */ is used for multi-line comment.
 Special Characters can be displayed on screen with backslash.

 Web browser is software which acts as mediator between client side code and server side code.
We can use any web browser like Internet Explorer, Mozilla Firefox or Google Chrome. When
we type the URL in the web browser, web browser sends a request to the web server. Then web
server runs the PHP script on that page. PHP module executes that script and sends the result
to the web browser which we can see on the screen.
 Code which is written within <?php…..?> tag is processed by web server. Code which is written
outside<?php…..?> tag is processed by web browser itself.

Example:
<html>
<head><title>Welcome to PHP Programming</title></head>
<body>
<h1><b>This is my first PHP program</b></h1>
<?php
echo "Hello Friends!!!!! PHP is very interesting language";
?>
</body></html>

Q – 9 How we can integrate HTML with PHP? Explain with example.


 When we want to design complex web pages, we need to use both HTML and PHP tags together
and it is quite easy.
 PHP script can be enclosed in <?php…….?>tag.
Integrating PHP code within HTML code

Prepared By: Bhumika S. Zalavadia Page 6


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 When we run the web page which contains both HTML and PHP tags in web browser, the web
browser only sends PHP code to web server which sends results to the web browser in return.
The HTML code is parsed and executed by the web browser itself and we get the final output.

Example:
<html>
<title> This is my first PHP code </title>
<body>
<?php
echo "Welcome in PHP world";
?>
</body>
</html>

Output: Welcome in PHP world


Integrating HTML code within PHP code
 We can also use different HTML tags in PHP code to customize our PHP output.

Example: <?php
echo " <b> One</b><br>";
echo " <i> Two </i><br> ";
echo " <u> Three </u><br> ";
?>

Output: One

Two

Three

Q – 10 What is variable? Give rules for naming the variables with example.
 Variable holds any type of data in PHP code. It can hold number, string, Boolean, objects or
resources.

Prepared By: Bhumika S. Zalavadia Page 7


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 In PHP variable begins with “$” sign and “=” sign is used to assign value to variable. “$” sign is
not the part of variable name but it is used to recognize that the string or character starts with $
is variable for PHP parser.
 In PHP we don’t need to declare the type of variable because it automatically takes the type of
assigned value. The value of variable may be changed at any time in code. Type casting is not
required in PHP code because it performs type casting automatically according to the assigned
data. So PHP is also known as Loosely Typed Language.
Rules for Variable Names
 Variable must start with letter or underscore(_).
 Digits from 0-9 are allowed in between the variable characters but variable name must not
start with digit.
 Space is not allowed within the variable name.
 We can’t user reserved words as variable names.
Example:
<?php
$a = 10;
$num = 'friend';
$_sum = 25.60;
$ab5 = "Happy Diwali";
$b = ture;
?>

Q – 11 Explain PHP data types.


PHP is also known as Loosely Typed Language. So we don’t need to declare the type of variable because
it automatically takes the type of assigned value. PHP supports following data types.
Data Type Description Example
Integer Integers are whole numbers without decimal point. $x = 10;
Double Doubles are floating point numbers. $x = 10.5;

Prepared By: Bhumika S. Zalavadia Page 8


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

Boolean Boolean has only two possible values: true or false $x = true;
$y = false;
NULL NULL means nothing not even 0. $x = null;
String String is sequence of characters. Single quoted $x = "Hello world!";
strings are treated as string constants while double $y = 'Hello world!';
quoted strings replace variable with their values.
Array Array is a collection of values. $color=array("Red","Blue","
Green");
Object Object is an instance of user defined class which is class Car
used to access the variables and functions of that {
class. function Car()
{
$this->color = "Red";
}
}
$c1 = new Car();
echo $c1->color;
Resource Resource is a special type of variable that holds -
references to resources external to PHP such as
database connections.

Q – 12 Explain echo and print output statements.


echo
 echo is used to print one or more strings or variable value.
 echo() is not actually a function (it is a language construct), so you are not required to use
parentheses with it.
 You can print multiple values with comma (“,”) operator.

Syntax: void echo ( arg1 [, arg2,…..] )

Prepared By: Bhumika S. Zalavadia Page 9


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

Example :
<?php
echo ("Hello World");
echo "This is Printing"."This is working";
echo "This is intersting","programming";
$a=10;
$b=20;
echo $a, $b;
?>

print
 print is used to print one or more strings or variable value.
 print() is not actually a function (it is a language construct), so you are not required to use
parentheses with it.
 You can’t print multiple values with comma operator but you can concate multiple values with
dot (.) operator.
 Print function returns integer value. The returned value is 1.
Syntax: int print ( arg )

Example:
<?php
print "Hello World";
print("Hello World");
$a=10;
$b=20;
$c = print $a;
print $c;
print $a.$b;
?>

Difference Between print and echo output statements

Prepared By: Bhumika S. Zalavadia Page 10


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

echo statement print statement


echo can display multiple values at a time. print can display only one value at a time.
Syntax: void echo ( string arg1 [, string ...]) Syntax: int print ( string arg)

It does not return any value. It returns integer value 1.


Example: Example:
$b=20; $b=20;
echo $b; $a=print ("Hello");
echo "Hello"; print $a; // display 1
print "Hello";
echo "Hello" , "Welcome"; // valid print "Hello" , "Welcome"; // invalid
echo "Hello" . "Welcome?"; // valid print "Hello" . "Welcome?"; // valid

You can print multiple values with comma You can’t print multiple values with comma
operator. You can also concate multiple values operator but you can concate multiple values
with dot (.) operator. with dot (.) operator.

Q – 13 Explain gettype() and settype() functions.


gettype()
This function returns the type of a variable. Returned type can any valid PHP data type like integer,
double, string, object, boolean etc.
Syntax: string gettype (anytype var )
Example:
<?php

$a = 10;
$b = 'Hello';
$c = 56.23;
$d = true;
echo gettype($a); //prints integer

Prepared By: Bhumika S. Zalavadia Page 11


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

echo gettype($b); // prints string


echo gettype($c); // prints double
echo gettype($d); // prints boolean
?>
settype()
This function is used to set the type of a variable. Any valid data type in PHP can be set. It returns TRUE
on success or FALSE on failure.
Syntax: bool settype( anytype var, string type )
Example:
<?php

$a = "bar"; // string
$b = true; //Boolean
echo gettype($a); //string
echo gettype($b); // boolean
settype($a,"integer");
settype($b, "string");
echo gettype($a); //integer
echo gettype($b); //string
?>

Q – 14 What do you mean by scope of variable? Explain global variables in PHP


with example.
Scope of variable means the context within which it can be used. The scope of variable depends on
where it is defined.
Global Variables
 The variable defined within the function becomes local variable and can be used within the
function only. We can’t get value of the local variable outside the function in which it is defined.
 The variables defined in the code outside of functions automatically become global and can be
used anywhere within the PHP script.

Prepared By: Bhumika S. Zalavadia Page 12


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

 You can use global keyword to declare any variable global directly when you want to use global
variable within the function.
Example:
<?php
$ x=10; //global variable
$ y=20; //global variable
function getvalue()
{
global $x , $y;
$x = $x +5;
$y = $y +5;

}
getvalue();
echo $x."<br>".$y;
?>

Output: x = 15

y =25

 As shown in above example variables x and y are global variables. These global variables can’t
be directly used within any function. As shown above if you want to get value of x and y within
the getvalue() then you have to declare them global again in function. If you will not do this step
then it will display the error like undefined variable x and undefined variable y. But if you
declare x and y as global in function then you will get x = 15 and y = 25 in output.
 In PHP, $GLOBALS is special associative super global array which holds all global variables
defined in the script. Name of the global variable is the key and the content of the global
variable is the value of the array element.
Accessing Global Variable from GLOBALS Array
Example:
<?php

Prepared By: Bhumika S. Zalavadia Page 13


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

$ x=10; //global variable


$ y=20; //global variable
function getvalue()
{
$GLOBALS['x'] = $GLOBALS['x'] +5;
$GLOBALS['y'] = $GLOBALS['y'] +5;
}
getvalue();
echo $x , $y;
?>
Note:
Superglobal Array Variables in PHP
Superglobal variables are built-in variables which are always available in all PHP scripts. Followings are
superglobal array variables.
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_SESSION
$_COOKIES
$_REQUEST
$_ENV

Q – 15 Explain static variables in PHP.


The scope of static variable is within the function but it does not lose its value when the function
returns. Static keyword is used to make any variable static.
Example:
<?php

Prepared By: Bhumika S. Zalavadia Page 14


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

function getvalue()
{
static $x = 0;
$x = $x + 5;
echo $x;
}
getvalue();
getvalue();
?>
Output: 5 10
 Static variable is initialized only once when the function is called first time and its value is
preserved even after function ends. As shown in above example x is static so outside the
getvalue() function we will get incremented value of x. If x is not declared as static then outside
the function we will get x=5 each time function is called.
 Static variables are generally used in recursive functions.

Q – 16 Explain constants in PHP.


 The variable declared as constant can’t be changed during the whole program execution.
 We can define constant using define() function or by using const keyword.
 Integer, float, string or Boolean data can be constant.
 We can get value of constant variable using constant() function. We can simply get value of
constant using its variable name also.
 Constant variable name can start from any alphabet or underscore. It can’t start from digit. All
the naming rules applicable to normal variable is also applicable to constant variable.
 Constant variable name does not need $sign.

Example:
<?php
const a=10;
define("ename","Atmiya");
echo ename."<br>";

Prepared By: Bhumika S. Zalavadia Page 15


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

echo constant("ename")."<br>";
echo a;
?>
Output: Atmiya
Atmiya
10
 PHP provides some in-built constants which can be used in any PHP script.

Constant Name Description


_ _LINE_ _ Returns current line number.
_ _FILE_ _ Returns full path and filename of the file.
_ _FUNCTION_ _ Returns function name.
_ _CLASS_ _ Returns class name.
_ _METHOD_ _ Returns method name.

Q – 17 Explain different types of operators in PHP.


PHP supports following types of operators.
 Arithmetic operators
 Comparison operators
 Logical (Relational)operators
 Assignment operators
 Conditional (Ternary)operators
Arithmetic Operators

Example Operator Result

-$a Negation (-) Opposite of $a.


$a + $b Addition (+) Sum of $a and $b.
$a - $b Subtraction (-) Difference of $a and $b.
$a * $b Multiplication (*) Product of $a and $b.

Prepared By: Bhumika S. Zalavadia Page 16


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

$a / $b Division (/) Quotient of $a and $b.


$a % $b Modulus (%) Remainder of $a divided by $b.
$a++ Unary Addition (++) Increment the value of a by 1.
$a-- Unary Subtraction (--) Decrement the value of a by 1.

Assignment Operators

Operator Example It is same as

= $x=$y $x=$y
+= $x += $y $x = $x + $y
-= $x -= $y $x= $x - $y
*= $x *= $y $x=$x * $y
/= $x /= $y $x=$x / $y
%= $x%=$y $x=$x % $y

Comparison Operators

Example Name Result

$a == $b Equal TRUE if $a is equal to $b.


$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Logical Operators

Prepared By: Bhumika S. Zalavadia Page 17


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

Example Name Result

$a and $b And TRUE if both $a and $b are TRUE.


$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

Ternary Operator or Conditional Operator


 One especial useful operator in ternary or conditional operator (?:).
 Its job is to takes three expression and use truth value of the first expression to decide which of
the other two expressions to evaluate and return.
Syntax:
Test-expression ? yes-expression : no-expression
 The value of this expression is the result of yes-expression if test-expression is true; otherwise
no-expression.
Example: Program to find whether a number is even or odd.
<?php

$n = 11;

echo $n % 2 == 0 ? "Even" : "Odd";

?>
String Operators
 There are two string operators.
 The first is the concatenation operator ('.'), which returns the concatenation of its right and left
arguments.
 The second is the concatenating assignment operator ('.='), which appends the argument on the
right side to the argument on the left side.
Example:
<?php

Prepared By: Bhumika S. Zalavadia Page 18


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

++

$a = "Hello ";
$b = $a. "World!"; // now $b contains "HelloWorld!"
echo $b;
$a = "Hello ";
$a.="World!"; // now $a contains "HelloWorld!"
echo $a;

?>

Q – 18 Explain different conditional structures in PHP.


Sometimes we need to perform some actions based on some decisions. For this conditional structures
are used. The most commonly used conditional structures are:
 If….else statement

 Switch statement
If Statement
The if construct is one of the most important features of many languages, PHP included. It allows for
conditional execution of code fragments. PHP features an if structure that is similar to that of C:
Syntax:
if (expression)
{
Statements;
}
expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute
statements, and if it evaluates to FALSE – it will ignore it.
Example:
<?php
$a =15;
$b =10;
if ($a > $b)
{
Prepared By: Bhumika S. Zalavadia Page 19
Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

echo "a is bigger than b";


}
?>

Output: 15 is greater than10


If…else Statement
Often you want to execute a statement if a certain condition is met and a different statement if the
condition is not met. This is what else is for.
Syntax:
if (expression)
{
Block1;
}
else
{
Block2;
}
If expression evaluates to TRUE then block1 is executed Else block2 is executed.
Example:
<?php
$a =10;
$b =15;
if ($a > $b)
{

echo "$a is bigger than $b";


}
else
{
echo "$b is greater than $a";

Prepared By: Bhumika S. Zalavadia Page 20


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

}
?>

Output: 15 is greater than10


If…elseif…else statement
If…elseif…else statement is a combination of if and else. When we have more than one conditions and
only one out of all will evaluate true then this statement is used.
Syntax:
if (expression)
{
Block1;
}
elseif
{
Block2;
}
elseif
{
Block3;
}
--------
---------
else
{
Block4;
}
Example:
<?php
$a = 10;
$b = 15;
if($a > $b)
{
Prepared By: Bhumika S. Zalavadia Page 21
Subject Name and Code: Advance Web Development (21DCECC503) Unit-1
echo "$a is bigger than $b";
}
elseif($a == $b)
{
echo "$a is equal to $b";

}
else
{
echo "$a is smaller than $b";

}
?>

Output: 10 is smaller than15


Switch Statement
The switch statement is similar to a series of IF statements on the same expression. In many occasions,
you may want to compare the same variable (or expression) with many different values, and execute a
different piece of code depending on which value it equals to. This is exactly what the switch statement
is for.
Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2;
}
Example:
<?php

Prepared By: Bhumika S. Zalavadia Page 22


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

$x = 2;
switch ($x)
{
case1:
echo "Number 1";
break;
case2:
echo "Number 2";
break;
case3:
echo "Number 3";
break;

default:
echo "No number between 1 and 3";
}
?>
Output: Number2

Q – 19 Explain different loop structures in PHP.


In programming often we need to execute the same block of code until some condition is met. For this
different looping statements are used in PHP. Followings are the most commonly used looping
statements in PHP.
 While loop
 Do…While loop
 For loop
 Foreach loop
While Loop
while loops are the simplest type of loop in PHP. They behave just like their C counterparts.
Syntax:
while (expr)

Prepared By: Bhumika S. Zalavadia Page 23


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

{
statements
}
 The meaning of a while statement is simple. It tells PHP to execute the nested statements
repeatedly, as long as the while expression evaluates to TRUE.
 The value of the expression is checked each time at the beginning of the loop, so even if this
value changes during the execution of the nested statements, execution will not stop until the
end of the iteration
 Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested
statements won't even be run once.
Example:
<?php

$i = 1;
while ($i <= 5)
{
echo $i++;
}
?>

Output: 1 2 3 45
Do…While Loop
 In Do…while loop expression is checked at the end of each iteration instead of in the beginning.
 The main difference from regular while loop is that do…while is executed at least once because
condition is checked at the end of loop.
Syntax:
do
{
statements
} while (expr);

Prepared By: Bhumika S. Zalavadia Page 24


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

Example:
<?php
$i = 5;
do
{
echo $i;
$i--;
} while ($i > 0);
?>

Output: 5 4 3 21
For Loop
 For loop is generally used when we know that how many time we want to iterate the loop.
Syntax:
for (initialization ; condition ; increment)
{
statements
}
 Initialization is the starting value of looping variable. Condition must be evaluated true to run
the loop. Increment is the number by which looping variable is incremented.
Example: Display numbers from 1 to 10
<?php
for ($i = 1; $i <= 10; $i++)
{
echo $i;
}
?>

Output: 1 2 3 4 5 6 7 8 9 10
Foreach Loop
This loop is used to iterate over an array elements. On each loop, the value of the current element is

Prepared By: Bhumika S. Zalavadia Page 25


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

assigned $value and the array pointer is advanced by one - so on the next loop, you'll be looking at the
next element.
Syntax:
foreach (array as value)
{
code to be executed;

}
Example: Print the values of the given array
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br>";
}
?>
Output: Value: one
Value: two
Value: three
Break Statement
Break statement ends execution of the current for, foreach, while, do-while or switch structure. Break
accepts an optional numeric argument which tells it how many nested enclosing structures are to be
broken out of.
Example:
<?php
for($i=0 ; $i<=10 ; $i++)
{
if($i = = 3)
break;
echo $i;

Prepared By: Bhumika S. Zalavadia Page 26


Subject Name and Code: Advance Web Development (21DCECC503) Unit-1

}
?>
Output: 0 1 2

Continue Statement
 Continue is used within looping structures to skip the rest of the current loop iteration and
continue execution at the condition evaluation and then the beginning of the next iteration.

Example:
<?php
for ($i = 0; $i < 5; $i++)
{
if ($i == 2)
continue;
echo$i;
}

?>
Output: 0 1 3 4
*********************************

Prepared By: Bhumika S. Zalavadia Page 27

You might also like