0% found this document useful (0 votes)
2K views

PHP Chap-1 Notes

This document provides an introduction to PHP, including: - PHP is an open source, server-side scripting language used to create dynamic web content that interacts with databases. - PHP was created in 1994 and originally stood for "Personal Home Page" but now stands for "Hypertext Preprocessor". It is commonly used for web application development. - PHP code is embedded into HTML files and is executed on the server-side to manage dynamic content, databases, sessions, e-commerce sites, and more. It is integrated with popular databases like MySQL.

Uploaded by

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

PHP Chap-1 Notes

This document provides an introduction to PHP, including: - PHP is an open source, server-side scripting language used to create dynamic web content that interacts with databases. - PHP was created in 1994 and originally stood for "Personal Home Page" but now stands for "Hypertext Preprocessor". It is commonly used for web application development. - PHP code is embedded into HTML files and is executed on the server-side to manage dynamic content, databases, sessions, e-commerce sites, and more. It is integrated with popular databases like MySQL.

Uploaded by

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

PHP VVFGC, Tumkur

Chapter- 1
Introduction to PHP
PHP is an open source , serverscripting a programing language that allow web-
developers to create dynamic content that interacts with the database.

History:

 PHP was developed by “Rasmus Lerdorf” in 1994.


 PHP was originally called “Personal home page” but now it stands for the
“hypertext preprocessor”.
 It is generally used for developing web-based software applications.
 It is written in the C-programming language.
 It is a server-side scripting language embedded in HTML. It manages dynamic
content databases, session tracking, e-commerce websites etc.
 It is integrated with a number of popular databases like MySQL, oracle, Sybase,
Informix, Microsoft sql server, and IIS [Internet Information Services] etc.

Advantages of PHP are:

 Open source: PHP is an open source software; it is readily available to all users with
free of cost. It opens to everyone, anytime, anywhere so that it is cost effective also.
 Platform independent (cross platform): It can run on various types of platform. It
is supported by all the operating systems like windows, Unix, solaris etc.
 Simple and easy: The one who knows any programming language can easily work
on PHP. It is simple because it is a loosely types language, easy to learn and write
the code.
 Database connectivity: PHP is easily connected with the database and make the
connection securely with the database.
 Fast: It is the fastest programming language as compared to another. The PHP
applications can be easily loaded over the slow internet and data speed.
 Maintenance: The PHP framework is mainly used to make the web-application
development easier and maintain the code automatically.
 Testing: The PHP based web applications can be easily tested and it performs the
unit testing quickly and easily.

K C Silpa, Asst. Professor, Dept. Of BCA Page 1


PHP VVFGC, Tumkur

 Security: The PHP frame work has built-in-tools to protect the web applications
from the outer attacks and security threats.

HTML relationship with PHP

When user wants to write a PHP code, he must know about the HTML without HTML user
cannot create the webpage both HTML and PHP languages are important for web-development.
The PHP code is embedded in HTML files.

Difference between HTML and PHP

HTML PHP
HTML is a markup language used to create PHP is an open source scripting language
static WebPages. used for the development of dynamic
Websites and dynamic web applications.
HTML is used for front end development or PHP is used for back end development or
Client side. Server side.
HTML is very easy to learn with less time it PHP is also easy to learn but not as much as
Accepts some small mistakes and gives the HTML it takes more time to learn and it
output. won’t accept the mistake in code.
HTML is compatible with almost all PHP also compatible with all types of
Browsers. Browsers.
HTML is used to organize the content of the PHP is used to “interact” with the database
websites. It focuses on how the contents need to retrieve the information, storing the data,
to display with different fonts, size and e-mail sending and provides the content to
colors etc. The HTML pages to display on the screen.
<html> <?PHP
<body>
-----------
</body>
?>
</html>

K C Silpa, Asst. Professor, Dept. Of BCA Page 2


PHP VVFGC, Tumkur

“AJAX”: (Asynchronous Java script and XML)

AJAX is a set of web-development techniques used in many web-technologies both client


and server side.

Client: To create asynchronous web-applications.

Server: To send and retrieve the data without interfering the display and behavior of existing
data.

Difference between Compiler and Interpreter

Interpreter Compiler
It takes a single line of code or instructions It takes an entire program as its input.
As input.
It does not generate any intermediate object It generates intermediate object code.
code
It requires less memory. [does not create It requires more memory in order to create
Object code]. Object code.
It displays the errors when each instruction It displays the errors once the entire
Is run. Program is checked.
Execution is slower. Execution is faster.
E.g.: Python, Ruby etc. E.g.: C, C++ etc.

PHP parser:

 A parser is a compiler or interpreter component that creates into the data of a smaller
element easy translation into another language.
 The parse means to analyze an object specifically.

K C Silpa, Asst. Professor, Dept. Of BCA Page 3


PHP VVFGC, Tumkur

Basic Syntax or Structure of PHP

1. The PHP files can contain text, HTML, CSS, Java script and PHP code.
2. The PHP files are stored by using the extension .php.
3. The PHP scripts can be placed anywhere in the document.
4. Each code line in PHP must end with a semicolon.
5. We use different styles to create PHP files.
a. Canonical PHP tags (Long form).
b. Short form.
c. Active server page style [ASP style].
a) Long form:
 It is always starting with <?php and ends with?>.
 Putting a PHP after the opening question mark makes PHP code friendly to the
XML parser.
 When PHP interpreter reads a file it only processes the lines between </php
and?> tags.
 For portability and compatibility always use these types of php format.
 E.g.: a) <?php
echo “Welcome to php”;

?>

b) Short form:
E.g.: a) <?
echo “ “;
?>

c) ASP style tags: These are used by active server pages to describe code blocks for
these we need to set the configuration of php.ini files.
E.g.: a) <%

-----------
%>

K C Silpa, Asst. Professor, Dept. Of BCA Page 4


PHP VVFGC, Tumkur

Using java scripts:

It is implemented using java script language; it is no more used now.

Syntax:

<script language=”php”>

---------------

</script>

How to run PHP files

 Install XAMPP or WAMP server and any code editors like Notepad, Notepad++ etc.
to computer system. 
 Write the PHP code in the code editor
Ex: <?php
echo “This is PHP and MySQL for BCA”;
?>
 Save this file by using the extension .php (test.php).
 All php files stored in htdocs folder by default.
 Then go to the XAMPP installation folder and run XAMPP.control.exe. 
 Now open any web browser then enter the file path, in address bar.
 If php installation and php files are working properly then the following output
is displayed. 

Output: This is PHP and MySQL for BCA

Comments

The user can use both single line and multi-line comments in php file.

E.g.: <?php

K C Silpa, Asst. Professor, Dept. Of BCA Page 5


PHP VVFGC, Tumkur

// This is single line comment.

# This is also single line comment.

/*This is multiline

Comment block

*/

?>

Variables in PHP

Variables are valid identifiers which are used to store the values like text, numbers and arrays.
 When a variable is declared it can be used again and again in the script.

Rules of declaring the variable:

1) A variable always begins with the dollar ($) sign.


2) A variable need not be declared before adding a value to it. Php automatically
converts the variable to the correct data type depending on its value.
3) PHP variable are case sensitive i.e. $a and $A are treated different.
4) It can contain only alpha numeric characters and underscores. (a-z, A-Z, 0-9, _) etc.
5) A variable name must begin with a letter or underscore and not with a number.

Syntax: $variable_name or $variable_name=values

Scope of the variables

The scope of the variable is the portion of the program in which the value of the variable
is accessed depending on the scope.

 PHP has 3 variable scopes:
1) Local variables.
2) Global variables.
3) Static variables.

K C Silpa, Asst. Professor, Dept. Of BCA Page 6


PHP VVFGC, Tumkur

1) Local variables: The variables declared within a function are called local variables to
that function. These variables cannot accessible outside the function.
E.g.: <?php
$num=10;
function local()
{
$num=20;
echo “the value of number is $num”;
}
local();
echo “the value of number is $num”;
?>
2) Global variables: The variables declared outside a function are called global
variables.
These variables can be accessed directly access outside a function.
but to access the global variable within a function we need to use the keyword
“global” before the variable.
E.g.: $num=20;
function global()
{
global $num;
$num++;
echo ” The value of number is $num”;
}
global();

Output: It display the result 21


if we omit the line global $num then the result will be 1 because $num++ would be
considered local variable within the function.
3) Static variable: The static variables are used to store the value of the variable even
after the completion of function execution. It able to retain its value between different
function calls. To declare a static variable we used the keyword static before the
variable name.
We can save the memory by using these variables.
K C Silpa, Asst. Professor, Dept. Of BCA Page 7
PHP VVFGC, Tumkur

E.g.: $sum=10;
function static()
{
$sum=20;
Static $count=0;
$count++;
echo “$count”;
echo “$sum”;
}
static ();
static ();
static ();

Quotations

a) Single quotes (‘ ‘): The contained inside the single quote is evaluated literally. It does
not represent the value assigned to the variable.
E.g.:
single quotes $string=”PHP”;
echo ‘$string is a scripting language’;
output: $string is a scripting language
b) Double quotes (“ “): The variables inside the double quotes are evaluated with
their values.
E.g.:
double quotes $string=”PHP”;
echo “$string is a scripting language”;
output: PHP is a scripting language
c) Backslash (escape character): escape characters are evaluated inside the
double quotes.
E.g.:
Backslashes $string=”PHP”;
1] echo ‘\$string is a scripting language’;
output: $string is a scripting language
2] echo “The $string is a \”dynamic\”webpage”;
output: The PHP is a “dynamic” webpage
K C Silpa, Asst. Professor, Dept. Of BCA Page 8
PHP VVFGC, Tumkur

Data types supported by PHP

 Data type: It defines the type of the data a variable can hold or stores.
 Categories of data types are:
a) Scalar- Integer, float, Boolean, string.
b) Compound- array, object.
c) Special- resources, NULL.
a) Scalar data types: This are used to represent a single value.
i. Integer: An integer can hold only whole numbers including positive and
negative numbers. It does not contain fractional part they can be decimal, octal or
hexadecimal. The range of integers must lie between -231 to +232.
E.g.: -42  negative decimal
0 x 742  octal
0 x CA8 hexa-decimal
ii. Float: It can also call double, floating points, real numbers. It can hold the
numbers containing fractional or decimal point, including positive and negative.
E.g.: 4.56, 4.0, 8.7e4, 1.23E+11
iii. Boolean: It hold only 2 values i.e. true or false. All successful events and non-
zero value will return true (1). Unsuccessful events are zero returns false.
iv. String: String is a sequence of characters. Each character in a string occupies 1
byte of storage. It can hold both characters and numbers. strings are written with
double quotes during its declaration.
E.g.: “PHP is a great language”
A particular character of the string can be accessed using array. E.g.: $color=”
maroon”;
$char=$color [2];
It assigns to the variable $char.
b) Compound / Complex data types: This data type allows multiple items of the
same type under a single entity.
i. Array: Array is a compound data type which can store multiple value of
same data type.
E.g.: $int array=array (10,20,30);
echo “First element: $array [0]”;
echo “Second element: $array [1]”;

K C Silpa, Asst. Professor, Dept. Of BCA Page 9


PHP VVFGC, Tumkur

Output: First element:10


Second element:20
ii. Object: Object is an instance of class which can hold both values, functions and
data structures. It is a concept of object-oriented programming language.
c) Special type:
i. Resources: resources are used to hold reference to some function call or external
php resources, such as database connections. Resources in php are not an exact
datatype.
E.g.: $res=dabase_connect();
ii. Null: a null is a special type of variable which has no values. It holds only
NULL. It is declared by using the keyword NULL.
E.g.: $num=10;
$num=NULL;// it assigns $num to NULL.

Type casting
It is a process of converting value of a variable from one data type to another is called as
type casting.

E.g.: Integer to float

As we know that in PHP, we do not need to specify the data type of a variable. The php
parser automatically set the data type but the data type of the variable can be converted to
another either manually or automatically using type casting.

Two types are:

1) Implicit type casting


2) Explicit type casting
1) Implicit type casting: Implicit is done by compiler itself according to the PHP code.
It is also called automatic type conversion.
E.g.: <?php
$x=2;
$y=4;
Var_dump($x/$y);
Var.dump($y/$x);
?>

K C Silpa, Asst. Professor, Dept. Of BCA Page 10


PHP VVFGC, Tumkur

2) Explicit type casting: Explicit type conversion is done by the programmer manually.
The data type you need to change the variable should be returned inside the
parenthesis before the variable (casting operator).
E.g.: <?php
$x=5.3;
$y=(int)$x; //casting $x into integer.
Var_dump($y);
?>

Automatic type conversion


It occurs when a variable is passed as an argument to a library function.

a) strval(): This function is used to convert a value to a string.


b) intval(): This function is used to convert a value to a integers.
c) floatval(): This function is used to convert a value to a floating point numbers.
d) boolval(): This function is used to convert a value to a Boolean.
e) var_dump(): This function is used to display the structured information (Type and
value) about one or more variables.

<?php
$val=88;
var_dump(strval($val));
?>
Output: String(88)

Super global or preset or predefined variables

 Super global variables are built-in variables that are always available in all scopes.
 User can access this variable from any function, class without declaring it
1) $GLOBAL
2) $_SERVER
3) $_REQUEST
4) $_GET
5) $_POST
6) $_SESSION

K C Silpa, Asst. Professor, Dept. Of BCA Page 11


PHP VVFGC, Tumkur

7) $_COOKIE
8) $_FILES
9) $_ENV

1) $GLOBAL:
 It is a super global variable is used to access global variables from any where in
PHP Script.
 PHP store all the global variables in array $GLOBALS [index] where index
holds the name of the variable.
E.g.: <?php
$x=75;
$y=25;
function add()
{
$GLOBALS[‘Z’]=$GLOBALS[‘X’]+$GLOBALS[‘Y’];
}
add();
echo $z;
?>

2) $_SERVER:
 It stores the information about headers, paths and script locations.
 E.g.:<?php
echo $_SERVER[‘PHP_SELF’];
echo $_SERVER[‘SERVER_NAME’];
echo $_SERVER[‘HTTP_HOST’];
echo $_SERVER[‘HTTP_REFERER’];
echo $_SERVER[‘HTTP_USER_AGENT’];
echo $_SERVER[‘SCRIPT_NAME’];
?>

a) PHP_SELF: returns the filename of the currently executing script.


b) SERVER_NAME: returns the name of the host server.
c) HTTP_HOST: returns the host header from the current request.

K C Silpa, Asst. Professor, Dept. Of BCA Page 12


PHP VVFGC, Tumkur

d) HTTP_REFERER: gives the complete URL of the page.


e) HTTP_USER_AGENT: gives the details of software and hardware versions.
f) SCRIPT_NAME: gives the path of the current script or page.

3) $_REQUEST:
It is used to collect the data after submitting a html form. It is not widely
$_GET and $_POST perform the same task.

4) $_GET:
 It is a default form request.
 The data passed through get request is visible on the URL browser, so it is not
secured.
 We can get limited amount of data through get request.

5) $_POST:
 Post request is widely used to submit form that have large amount of data such as file
upload, image upload etc.
 The data passed through post request is not visible on URL so it is secured.

 We can send large amount of data through this.

6) $_SESSION:
 It is a way to store the information to be used at the multiple pages.
 By default, session variables will be lost after closes the browser.
 Session_start() must be the very first in the document before any HTML tags.

7) $_COOKIE:
 Cookies are small text files loaded from a server to a client computer.
 It stores the information regarding the client computer so that the same page is visited
by the user again and again. It decreases the latency period to open the page.
8) $_FILES:
 It is used to upload the files.
 It is associated with 2-D array and it keeps all the information related to the uploaded
file.

K C Silpa, Asst. Professor, Dept. Of BCA Page 13


PHP VVFGC, Tumkur

9) $_ENV: it is a super global variable that contains the environment variable where that
environment variable is provided by the shell under which php is running.

Constant
 A constant is an identifier for a simple value. The value cannot be changed during the
execution.
 The valid constant name starts with a letter or underscores (no dollar sign before the
constant)
 To create a php constant use the define () and const keyword.
define():
it is a function to create a constant. It defines a constant at runtime.
Syntax:

define (name, value, case insensitive)

 Where, name: it specifies the name of the constant.

 Value: it specifies the value of the constant.

 Case sensitive: it specifies whether the constant name should be insensitive the default
is false.

define(“MESSAGE”, “hello”);

const:
it is a keyword used to create a constant. It defines a constant at compile time.
Syntax:
const name = value;

K C Silpa, Asst. Professor, Dept. Of BCA Page 14


PHP VVFGC, Tumkur

Operators
Operator is a symbol that performs an even action on a value.

Types of operators are:

Arithmetic operators: are used to perform simple mathematical calculations.

operator syntax example Description


+ $x+$y 5+4=9 Sum of 2 operands
- $x-$y 5-4=1 Difference of 2 operands
* $x*$y 5*4=20 Multiply 2 operands
/ $x/$y 4/2=2 It gives quotient
% $x%$y 5%3=2 It gives remainder
** $x**$y 5**3=125 5 raised to the power 3
3
(exponentiation) 5

Logical operators: are used to combine 2 or more expressions.

operator Name Example Description


&& Logical AND $x&&$y True if both inputs are true, otherwise false
|| Logical OR $x||$y False, if both input is false, otherwise true
! Logical Not !$x Returns negation
(T-> f) (f-> T)
v Logical XNOR $x v $y It returns T for even numbers of I‟s , otherwise
false
^ XOR $x^$y It returns 0 for even no. of 1‟s returns 1 for the
odd no. of 1‟s

x y x&y x||y x^y Xvy


0 0 0 0 1 0
0 1 0 1 0 1
1 0 0 1 0 1
1 1 1 1 1 0

K C Silpa, Asst. Professor, Dept. Of BCA Page 15


PHP VVFGC, Tumkur

Relational operators: these are used to compare 2 elements then the output is in the form of
Boolean.

Operator Name Syntax Operation


=== Identical $x= = =$y It returns true if both
the operands values
are equal and of the
Same type.
!= = NOT Identical $x!= =$y It returns true if both
the operands values
are not equal and of
The different
data type.
== Equal to $x= =$y It returns true if both
The values are equal.
!= Not Equal to $x!=$y It returns true if both
The values are not
equal.
< Less than $x<$y It returns true if $x is
less than $y.
> Greater than $x>$y It returns true if $x is
greater than $y.
<= Less than or equal to $x<=$y It returns true if $x is
less than or equal to
$y.
>= Greater than or equal $x>=$y It returns true if $x is
to greater than or equal
to $y.

Identical / Identity: The identity operator compares the variables first then it compares the
type of the variable. If the type of the variable is different then it returns false.

E.g.:

1) “22”===22 it returns false because “22” is of type string (within quotes).


22 is of type int (without quotes).

2) 22===22  it returns true, both are of type int.


3) “22”===String(22)it returns true, both of String type.
Assignment operators (short hand):

These operators provide and easy method to assign a value and It makes to perform basic
arithmetic and string operation easily.

Operator Name Syntax Operation


= Assign $x=$y Right operand value
assigns to left

K C Silpa, Asst. Professor, Dept. Of BCA Page 16


PHP VVFGC, Tumkur

operand.
+= Add then assign $x+=$y Is same as
$x=$x+$y.
-= Subtract then assign $x-=$y Is same as $x=$x-
$y.
*= Multiply then assign $x*=$y Is same as
$x=$x*$y.
/= Divide then assign $x/=$y Is same as $x=$x/$y.
%= Modulus then assign $x%=$y Is same as
$x=$x%$y.
>>= Perform right shift $x>>=$y Is same as
then assign $x=$x>>$y.
<<= Perform left shift $x<<=$y Is same as
then assign $x=$x<<$y.

Bitwise operator: it is used to perform on its bit level. An operators are first converted to bit
level them calculation is performed on the operands.

operator Name Syntax Operation


& Bitwise AND $x&$y It returns 1, only if both bits 1.
| Bitwise OR $x | $y It returns 1, if any of the 2 bits is 1.
^ Bitwise XOR $x ^ $y It returns 0, for the same bits.

~ Bitwise NOT ~$x If performs 1’s complement on the


input.
<< Bitwise left shift $x <<$y The left operands value is moved left
by the number of bits specified by the
right operand.
>> Bitwise right shift $x>>$y The left operand values moved right
by the number of bits specified by the
right operand.

Eg: $x=1010

$y=1100

Bitwise AND: 1010

1100

K C Silpa, Asst. Professor, Dept. Of BCA Page 17


PHP VVFGC, Tumkur

1000

Bitwise XOR: 1010

1100

0110

Bitwise XOR: 1010

1100

0110

Bitwise NOT: 1010

0101

Eg: $x <<2

$x 1010

101000

$x >>2

$x 1010

001010

Bitwise left shift:

Syntax Binary format Value


X=7 00000111 7
X=x<<1 00001110 14
X=x<<3 01110000 112
X=x<<2 11000000 192

Bitwise right shift:

Syntax Binary format Value

K C Silpa, Asst. Professor, Dept. Of BCA Page 18


PHP VVFGC, Tumkur

X=192 11000000 192


X=x>>1 01110000 96
X=x>>3 00001110 24
X=x>>2 00000111 3

String operator:
There are 2 string operators in php are:

operators name syntax Operation


. concatenation $x. $y Concatenates the string $x and
$y
.= Concatination and assign $x.=$y Concatenates $x and $y then
assigns to $x

Conditional operator/Ternary operator:

Syntax: (condition) value1 (t): value2 (f);

 The ternary operators are used to operate on 3 operands.


 If the condition is true the value 1 is executed
 If the condition is false then value 2 is executed.

Space Ship Operators:

 It is only available in the new version of php.


 It is used to compare 2 expressions
 Php7 has introduced a new kind of operator called spaceship operator.

It returns integer values instead of Boolean result

Operator Syntax Operation


$x< $y $x< = >$y Identical to -1
$x>$y $x< = >$y Identical to 1
$x= =$y $x< = >$y Identical to 0

K C Silpa, Asst. Professor, Dept. Of BCA Page 19


PHP VVFGC, Tumkur

Control Structure

Control sequence allows user to execute block of code depending on conditions. It control
the flow of code, order in which the various statement are execute how many times a
particular code should execute when the code block will ended.

There are 3 types of control structure, they are:

 Conditional / decision making statements


 Looping statements
 Jumping statements

Conditional statements: it is used to perform different actions based on different conditions


it breaks based on different condition it breaks the sequential flow of programs and jumps to
the different code based on the condition of input value.

 If statement
 If else statement
 If else ladder statement

 Switch statement

If statement: it executes the block of statement depending on the condition it executes the
statement only it specifies condition is true.

if (condition)
{
Code to be executed;
}
Ex:
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>

K C Silpa, Asst. Professor, Dept. Of BCA Page 20


PHP VVFGC, Tumkur

If else statement: in this structure the true block statements are execute if the condition are
true otherwise else part get executed.

Syntax:

if (cond)
{
code is true;

}
else
{
code is false;
}
Ex:
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>

If - else if ladder statement:

It is a multiway decision maker which contains two or more else if condition in which any
one code block will be executed based on the condition if all the condition becomes false then
the last code block will be executed.

Syntax:

if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....

K C Silpa, Asst. Professor, Dept. Of BCA Page 21


PHP VVFGC, Tumkur

} else{
//code to be executed if all given conditions are false
}

Ex:
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>

K C Silpa, Asst. Professor, Dept. Of BCA Page 22


PHP VVFGC, Tumkur

Switch statement: switch statement is used to select one block of code among multiple
blocks.
Syntax:

switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}

Important points to be noticed about switch case:


1. The default is an optional statement. Even it is not important, that default must always be
the last statement.
2. There can be only one default in a switch statement. More than one default may lead to
a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the statements will
execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less
readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.

Ex:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
K C Silpa, Asst. Professor, Dept. Of BCA Page 23
PHP VVFGC, Tumkur

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");
}
?>
Looping statements

They are executes a block of code for specific times until the condition becomes false
It helps to execute the code again and again.
It avoids rewriting the code.
There are 4 loop statements:
o While
o Do-while
o For
o Foreach
While loop: it executes a block of code as long as the condition is true
It is also called as entry controlled loop.

Syntax:

while(condition){
//code to be executed
}

Ex:

K C Silpa, Asst. Professor, Dept. Of BCA Page 24


PHP VVFGC, Tumkur

<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Do-while loop: it always execute the block of code at least once. It repeats the loop as long as the
condition is true. It checks the condition at the end of the code
It is also called as exit controlled loop.
Syntax:
do{
//code to be executed
}while(condition);

Ex:

<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
For loop: it is used to execute the block of code for a certain number of time. It is also called
as fixed loop

Syntax:

for(initialize; condition; inc/dec)


{
Code;
}
Where, initialization is used to set the start value of the variable.

Condition evaluates the for iteration, if it is true then executes the code until it becomes false

Inc/dec is used to update the present values of variable

K C Silpa, Asst. Professor, Dept. Of BCA Page 25


PHP VVFGC, Tumkur

Ex:

<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
For each loop: it is used to iterate over arrays.
The value of the current array element is assigned to the variable($value) and shifted to the
next element.

Syntax:

foreach(array-elements as $value)
{
Code;
}
Foreach statement excepts an array-element
The keyword as and definition of the variable to receive the value.
Ex:

<?php
$x=array(“ one” ,” two” ,” three” ;
foreach($x as $value)
{
echo$value;
}
?>
Jumping statements: it is used to transfer the control from one point to another point in
the program.

 Break
 Continue
 Goto
Break: it is used to terminate the execution of a loop at that point itself. It immediately
coming out of a loop.

Eg:

<?php
$i=0;
while($i<5)
{

K C Silpa, Asst. Professor, Dept. Of BCA Page 26


PHP VVFGC, Tumkur

$i++;
if($i==3)
break;
echo $i;
}
?>
o/p:
1
2
Continue: it is used to stop the current iteration and starts the next iteration until condition
becomes false.

Note: Always break and continue keywords are preceded by a conditional statement.

Ex:

<?php
$i=0;
while($i<=5)
{
$i++;
if($i==3)
continue;
echo $i;
}
?>
o/p:

Goto: it allows making an absolute jump to another point in the program.


goto transfer the control from one statement to other within the program by ignoring any type
of nesting limitations.
A label must be a valid identifier followed by colon (: ).

Syntax:

Statement 1;

Goto labelname;

K C Silpa, Asst. Professor, Dept. Of BCA Page 27


PHP VVFGC, Tumkur

Statement2;

Labelname:

statements;

Ex:

<?php
$i=0;
while($i<=10)
{
$i++;
if($i==10)
goto stop;
else
echo $i;
}
stop: echo “ value is greater than 10 hence stopped” ;
?>
o/p;

Value is greater than 10 hence stopped

K C Silpa, Asst. Professor, Dept. Of BCA Page 28

You might also like