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

PHP Unit 1

The document provides an introduction to PHP including what PHP is used for, a brief history of PHP, its lexical structure, data types, variables, expressions, operators, flow control statements, and how to include code. It covers the basics of PHP including server-side scripting, command line scripting, and client-side GUI applications. It also discusses PHP's origins in the mid-1990s and its evolution over time.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PHP Unit 1

The document provides an introduction to PHP including what PHP is used for, a brief history of PHP, its lexical structure, data types, variables, expressions, operators, flow control statements, and how to include code. It covers the basics of PHP including server-side scripting, command line scripting, and client-side GUI applications. It also discusses PHP's origins in the mid-1990s and its evolution over time.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PHP Unit 1 1 GSC BCA

Contents
What Does PHP Do? ............................................................................................................... 1
A brief history of PHP ............................................................................................................. 1
Lexical Structure ..................................................................................................................... 2
Case Sensitivity ................................................................................................................... 2
Statements and Semicolons ............................................................................................... 2
Whitespace and Line Breaks ............................................................................................... 2
Comments........................................................................................................................... 3
Literals ................................................................................................................................ 4
Identifiers............................................................................................................................ 4
Variable names ................................................................................................................... 4
Function names .................................................................................................................. 4
Class names ........................................................................................................................ 4
Constants ............................................................................................................................ 5
Keywords ............................................................................................................................ 5
PHP Data Types ...................................................................................................................... 5
PHP String ........................................................................................................................... 6
PHP Integer ......................................................................................................................... 6
PHP Float............................................................................................................................. 6
PHP Boolean ....................................................................................................................... 6
PHP Array ............................................................................................................................ 7
PHP object .......................................................................................................................... 7
PHP Null .............................................................................................................................. 7
PHP Resource...................................................................................................................... 7
Variables ................................................................................................................................. 8
Variable Variables ............................................................................................................... 8
Variable References ............................................................................................................ 8
Expressions and Operators .................................................................................................... 9
Operator Associativity ........................................................................................................ 9
Implicit Casting ................................................................................................................... 9
PHP Operators ........................................................................................................................ 9
PHP Arithmetic Operators .................................................................................................. 9
PHP Assignment Operators .............................................................................................. 10
PHP Unit 1 2 GSC BCA

PHP Comparison Operators .............................................................................................. 10


PHP Increment / Decrement Operators ........................................................................... 11
PHP Logical Operators ...................................................................................................... 11
PHP String Operators ........................................................................................................ 11
PHP Array Operators ........................................................................................................ 12
PHP Conditional Assignment Operators ........................................................................... 12
Flow-Control Statements ..................................................................................................... 13
Conditional Statement ......................................................................................................... 13
PHP If Statement .............................................................................................................. 13
PHP If-else Statement ....................................................................................................... 13
PHP If-else-if Statement ................................................................................................... 14
PHP nested if Statement................................................................................................... 15
PHP Switch ........................................................................................................................ 15
Loops .................................................................................................................................... 16
PHP While Loop ................................................................................................................ 16
PHP do-while loop ............................................................................................................ 17
Difference between while and do-while loop .................................................................. 18
PHP For Loop .................................................................................................................... 18
PHP Nested For Loop ........................................................................................................ 19
PHP foreach loop .............................................................................................................. 19
PHP try-catch ........................................................................................................................ 20
Declare ................................................................................................................................. 22
exit and return...................................................................................................................... 22
Goto ...................................................................................................................................... 23
PHP Include and Require ...................................................................................................... 23
PHP include ....................................................................................................................... 23
PHP require ....................................................................................................................... 24
PHP Unit 1 1 GSC BCA

Unit 1 - Basics of PHP


Introduction to PHP – what does PHP Do? – a brief history of PHP – language basics –
lexical structure – data types – variables – expressions and operators – flow control
statements – including code – embedding PHP in web pages.

What Does PHP Do?

PHP can be used in three primary ways:

Server-side scripting
PHP was originally designed to create dynamic web content, and it is still best suited for
that task. To generate HTML, you need the PHP parser and a web server through which
to send the coded documents. PHP has also become popular for generating XML
documents, graphics, Flash animations, PDF files, and so much more.

Command-line scripting
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You
might use the command-line scripts for system administration tasks, such as backup
and log parsing; even some CRON job type scripts can be done this way (nonvisual PHP
tasks).

Client-side GUI applications


Using PHP-GTK, you can write full-blown, cross-platform GUI applications in PHP.

A brief history of PHP

PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Early non-released
versions were used on his home page to keep track of who was looking at his online
resume. The first version used by others was available sometime in early 1995 and was
known as the Personal Home Page Tools. The parser was rewritten in mid-1995 and
named PHP/FI Version 2. The FI came from another package Rasmus had written which
interpreted html form data. He combined the Personal Home Page tools scripts with the
Form Interpreter and added mSQL support and PHP/FI was born. PHP/FI grew at an
amazing pace and people started contributing code to it.

It is estimated that by late 1996 PHP/FI was in use on at least 15,000 web sites around
the world. By mid-1997 this number had grown to over 50,000. Mid-1997 also saw a
change in the development of PHP. The parser was rewritten from scratch by Zeev
Suraski and Andi Gutmans and this new parser formed the basis for PHP Version 3. A lot
of the utility code from PHP/FI was ported over to PHP3 and a lot of it was completely
rewritten.

Today (end-1999) either PHP/FI or PHP3 ships with a number of commercial products
such as C2's StrongHold web server and RedHat Linux. A conservative estimate based
on an extrapolation from numbers provided by NetCraft would be that PHP is in use on
over 1,000,000 sites around the world.
PHP Unit 1 2 GSC BCA

Lexical Structure

The lexical structure of a programming language is the set of basic rules that governs
how you write programs in that language. It is the lowest-level syntax of the language
and specifies such things as what variable names look like, what characters are used for
comments, and how program statements are separated from each other.

Case Sensitivity
The names of user-defined classes and functions, as well as built-in constructs
and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three
lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");

Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and
$NaME are three different variables.

Statements and Semicolons


A statement is a collection of PHP code that does something. Here is a small
sample of PHP statements, including function calls, assignment, and an if statement:

echo "Hello, world";


myFunction(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) {
echo "Rhyme? And Reason?";
}

PHP uses semicolons to separate simple statements.

Whitespace and Line Breaks


In general, whitespace doesn’t matter in a PHP program. You can spread a
statement across any number of lines, or lump a bunch of statements together on a
single line.

For example, this statement:


raisePrices($inventory, $inflation, $costOfLiving, $greed);
could just as well be written with more whitespace:
raisePrices (
$inventory ,
$inflation ,
$costOfLiving ,
$greed
) ;
PHP Unit 1 3 GSC BCA

Comments
Comments give information to people who read your code, but they are ignored
by PHP at execution time.
PHP provides several ways to include comments within your code as -

Shell-style comments
When PHP encounters a hash mark character (#) within the code, everything
from the hash mark to the end of the line or the end of the section of PHP code
(whichever comes first) is considered a comment. This method of commenting is found
in Unix shell scripting languages and is useful for annotating single lines of code or
making short notes.
Because the hash mark is visible on the page, shell-style comments are
sometimes used to mark off blocks of code:

#######################
## Cookie functions
#######################

Sometimes they’re used before a line of code to identify what that code does, in which
case they’re usually indented to the same level as the code:
if ($doubleCheck) {
# create an HTML form requesting that the user confirm the action
echo confirmationForm();
}

C++ comments
When PHP encounters two slashes (//) within the code, everything from the
slashes to the end of the line or the end of the section of code, whichever comes first, is
considered a comment. This method of commenting is derived from C++. The result is
the same as the shell comment style.
Here are the shell-style comment examples, rewritten to use C++ comments:

////////////////////////
// Cookie functions
////////////////////////

if ($doubleCheck) {
// create an HTML form requesting that the user confirm the
action
echo confirmationForm();
}

C comments
When PHP encounters a slash followed by an asterisk (/*), everything after that,
until it encounters an asterisk followed by a slash (*/), is considered a comment. This
kind of comment can span multiple lines.

Here’s an example of a C-style multiline comment:


/* In this section, we take a bunch of variables and
assign numbers to them. There is no real reason to
PHP Unit 1 4 GSC BCA

do this, we're just having fun.*/


$a = 1;
$b = 2;
$c = 3;
$d = 4;

Literals
A literal is a data value that appears directly in a program. The following are all
literals in PHP:

2001 "Hello World" null


0xFE 'Hi'
1.4142 true

Identifiers

An identifier is simply a name. In PHP, identifiers are used to name variables,


functions, constants, and classes. The first character of an identifier must be an
uppercase or lowercase, the underscore character (_), or any of the characters between
ASCII 0x7F and ASCII 0xFF. After the initial character, these characters and the digits 0–
9 are valid.

Variable names
Variable names always begin with a dollar sign ($) and are case-sensitive. Here
are some valid variable names:
$bill $MaximumForce $_underscore
$head_count $I_HEART_PHP $_int

Here are some illegal variable names:


$not valid
$|
$3wa

These variables are all different due to case sensitivity:


$hot_stuff $Hot_stuff $hot_Stuff $HOT_STUFF

Function names
Function names are not case-sensitive. Here are some valid function names:
tally LOWERCASE_IS_FOR_WIMPS
list_all_users _hide
deleteTclFiles
These function names refer to the same function:
Howdy HoWdY HOWDY HOWdy howdy
Class names
Class names follow the standard rules for PHP identifiers and are also not case-
sensitive.
PHP Unit 1 5 GSC BCA

Here are some valid class names:


Person account
Constants
A constant is an identifier for a simple value; only scalar values—Boolean,
integer, double, and string—can be constants. Once set, the value of a constant cannot
change. Constants are referred to by their identifiers and are set using the define()
function:

define('PUBLISHER', "O'Reilly & Associates");


echo PUBLISHER;

Keywords
A keyword (or reserved word) is a word set aside by the language for its core
functionality—you cannot give a variable, function, class, or constant the same name as
a keyword. Table 2-1 lists the keywords in PHP, which are case-insensitive.

Table 2-1. PHP core language keywords


__CLASS__ endfor public goto
__DIR__ endforeach require if
__FILE__ endif require_once implements
__FUNCTION__ endswitch return include
__LINE__ endwhile callable include_once
__METHOD__ eval() case instanceof
__NAMESPACE__ exit() catch static
__TRAIT__ extends class switch
__halt_compiler() final clone throw
abstract insteadof const trait
and interface continue try
array() isset() declare unset()
as list() default use
break namespace die() var
echo new do while
else or for xor
elseif print foreach
empty() private function
enddeclare protected global

PHP Data Types

Variables can store data of different types, and different data types can do different
things.

PHP supports the following data types:

1. String 5. Array
2. Integer 6. Object
3. Float 7. NULL
4. Boolean 8. Resource
PHP Unit 1 6 GSC BCA

PHP String
A string is a sequence of characters, like "Hello world!". A string can be any text
inside quotes. You can use single or double quotes:
Output:
<?php
$x = "Hello world!"; Hello world!
$y = 'Hello world!'; Hello world!
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.

Rules for integers:


1. An integer must have at least one digit
2. An integer must not have a decimal point
3. An integer can be either positive or negative
4. Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal
(base 8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:

<?php Output:
$dec1 = 34;
$oct1 = 0243; Decimal number: 34
$hexa1 = 0x45; Octal number: 163
echo "Decimal number: " .$dec1. "</br>"; HexaDecimal number:
echo "Octal number: " .$oct1. "</br>"; 69
echo "HexaDecimal number: " .$hexa1. "</br
>";
?>

PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can
hold numbers with a fractional or decimal point, including a negative or positive sign.

<?php Output:
$n1 = 19.34;
$n2 = 54.472; Result: 73.812
$sum = $n1 + $n2;
echo "Result: " .$sum;
?>
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values:
TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition is
correct, it returns TRUE otherwise FALSE.
PHP Unit 1 7 GSC BCA

<?php Output:
if (TRUE)
echo "This condition is TRUE."; This condition is
if (FALSE) TRUE.
echo "This condition is FALSE.";
?>
PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.

<?php Output:
$bikes = array("Suzuki", "Yamaha", "KTM");
echo "Element1: $bikes[0] </br>"; Element1: Suzuki
echo "Element2: $bikes[1] </br>"; Element2: Yamaha
echo "Element3: $bikes[2] </br>"; Element3: KTM
?>
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.

<?php Output:
class bike {
function model() { Bike Model: Yamaha
$model_name = "Yamaha";
echo "Bike Model: "
.$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive. The special type of data type NULL
defined a variable with no value.

<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources.
PHP Unit 1 8 GSC BCA

Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here,
some important points to know about variables:

1. As PHP is a loosely typed language, so we do not need to declare the data types of
the variables.
2. After declaring a variable, it can be reused throughout the code.
3. Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:


$variablename=value;

Rules for declaring PHP variable:

1. A variable must start with a dollar ($) sign, followed by the variable name.
2. It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
3. A variable name must start with a letter or underscore (_) character.
4. A PHP variable name cannot contain spaces.
5. Variable name cannot start with a number or special symbols.
6. PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.

Example to store string, integer, and float values in PHP variables.

<?php Output:
$str="hello string";
$x=200; string is: hello
$y=44.6; string
echo "string is: $str <br/>"; integer is: 200
echo "integer is: $x <br/>"; float is: 44.6
echo "float is: $y <br/>";
?>
Variable Variables
You can reference the value of a variable whose name is stored in another
variable by prefacing the variable reference with an additional dollar sign ($). For
example:
$foo = "bar";
$$foo = "baz";
After the second statement executes, the variable $bar has the value "baz".

Variable References
In PHP, references are how you create variable aliases. To make $black an alias
for the variable $white, use:
$black =& $white;
PHP Unit 1 9 GSC BCA

Expressions and Operators


An expression is a bit of PHP that can be evaluated to produce a value. The
simplest expressions are literal values and variables.
An operator takes some values (the operands) and does something (for instance,
adds
them together).

Operator Associativity
Associativity defines the order in which operators with the same order of
precedence are evaluated.

Implicit Casting
PHP’s variables can store integers, floating-point numbers, strings, and more,
and to keep as much of the type details away from the programmer as possible, PHP
converts values from one type to another as necessary.
The conversion of a value from one type to another is called casting. This kind of
implicit casting is called type juggling in PHP.

PHP Operators

Operators are used to perform operations on variables and values. PHP divides the
operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional assignment 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


PHP Unit 1 10 GSC BCA

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.

Same
Assignment Description
as...

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

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

=== Identical $x === Returns true if $x is equal to $y, and they are of
$y the 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

!== Not identical $x !== Returns true if $x is not equal to $y, or they are
$y not of 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 $x >= $y Returns true if $x is greater than or equal to $y


or equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to
PHP Unit 1 11 GSC BCA

<=> Spaceship $x <=> Returns an integer less than, equal to, or greater
$y than zero, depending on if $x is less than, equal
to, or greater than $y. Introduced in PHP 7.

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

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.
Operator Name Example Result

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

xor Xor $x xor $y True if either $x or $y is true, but not 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

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 .= Appends $txt2 to $txt1


assignment $txt2
PHP Unit 1 12 GSC BCA

PHP Array Operators


The PHP array operators are used to compare arrays.

Operator Name Example Result

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

== Equality $x == $y Returns true if $x and $y have the same key/value


pairs

=== Identity $x === Returns true if $x and $y have the same key/value
$y 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- $x !== Returns true if $x is not identical to $y


identity $y

PHP Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on
conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE

?? Null $x = expr1 ?? expr2 Returns the value of $x.


coalescing The value of $x is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or is NULL, the
value of $x is expr2.
Introduced in PHP 7
PHP Unit 1 13 GSC BCA

Flow-Control Statements
Conditional statements, such as if/else and switch, allow a program to execute
different pieces of code, or none at all, depending on some condition. Loops, such as
while and for, support the repeated execution of particular segments of code.

1. Conditional statements
a. if statement - executes some code if one condition is true
b. if...else statement - executes some code if a condition is true and another
code if that condition is false
c. if...elseif...else statement - executes different codes for more than two
conditions
d. switch statement - selects one of many blocks of code to be executed
2. Loop
a. while - loops through a block of code as long as the specified condition is
true
b. do...while - loops through a block of code once, and then repeats the loop
as long as the specified condition is true
c. for - loops through a block of code a specified number of times
d. foreach - loops through a block of code for each element in an array

Conditional Statement

PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.

Syntax
if(condition){
//code to be executed
}

Example
<?php Output:
$num=12;
if($num<100){ 12 is less than 100
echo "$num is less than
100";
}
?>
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false. It executes one
block of code if the specified condition is true and another block of code if the condition
is false.
Syntax
if(condition){
PHP Unit 1 14 GSC BCA

//code to be executed if true


}else{
//code to be executed if false
}
Example

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

PHP If-else-if Statement


The PHP if-else-if is a special statement used to combine multiple if?.else
statements. So, we can check multiple conditions using this statement.

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
....
} else{
//code to be executed if all given conditions are false
}

Example

<?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";
PHP Unit 1 15 GSC BCA

}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>

Output:

B Grade

PHP nested if Statement


The nested if statement contains the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.

Syntax

if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}

Example

<?php Output:
$age = 23;
$nationality = "Indian"; Eligible to give
//applying conditions on nationality and vote
age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions.
It works like PHP if-else-if statement.

Syntax
PHP Unit 1 16 GSC BCA

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

This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the values for
each case in the structure. If there is a match, the block of code associated with that case
is executed. Use break to prevent the code from running into the next case
automatically. The default statement is used if no match is found.

Example

<?php Output:
$num=20;
switch($num){ number is equal to
case 10: 20
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");
}
?>

Loops

PHP While Loop


PHP while loop can be used to traverse set of code like for loop. It should be used if the
number of iterations is not known. The while loop is also called an Entry control loop
because the condition is checked before entering the loop body. This means that first
the condition is checked. If the condition is true, the block of code will be executed.

Syntax
while(condition){
//code to be executed
PHP Unit 1 17 GSC BCA

Example 1

<?php Output:
$n=1;
while($n<=5){ 1
echo "$n<br/>"; 2
$n++; 3
} 4
?> 5
Example 2 – printing alphabets using while loop.

<?php Output:
$i = 'A';
while ($i < 'F') { A
echo $i; B
$i++; C
echo "</br>"; D
} E
?>

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop. It executes
the code at least one time always because the condition is checked after executing the
code.

Syntax
do{
//code to be executed
}while(condition);

Example

<?php Output:
$n=1; 1
do{ 2
echo "$n<br/>"; 3
$n++; 4
}while($n<=5); 5
?>
PHP Unit 1 18 GSC BCA

Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as entry The do-while loop is also named as exit
control loop. control loop.

The body of the loop does not execute if The body of the loop executes at least once,
the condition is false. even if the condition is false.

Condition checks first, and then block of Block of statements executes first and then
statements executes. condition checks.

This loop does not use a semicolon to


terminate the loop.

PHP For Loop

Syntax

for(initialization; condition; increment/decrement){


//code to be executed
}

initialization - Initialize the loop counter value. The initial value of the for loop is done
only once. This parameter is optional.

condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise the execution of the
loop ends.

Increment/decrement - It increments or decrements the value of the variable.

Example 1

<?php Output:
for($i=1;$i<=3;$i++){
echo "$n<br/>"; 1
} 2
?> 3
Example 2
All three parameters are optional, but semicolon (;) is must to pass in for loop. If
we don't pass parameters, it will execute infinite.

<?php
$i = 1;
//infinite loop
for (;;) {
PHP Unit 1 19 GSC BCA

echo $i++;
echo "</br>";
}
?>

Output:

1
2
3
.
.

PHP Nested For Loop


We can use for loop inside for loop in PHP, it is known as nested for loop. The
inner for loop executes only when the outer for loop condition is found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for
loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner
for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop
and 3 times for 3rd outer loop).

Example

<?php Output:
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){ 1 1
echo "$i $j<br/>"; 1 2
} 1 3
} 2 1
?> 2 2
2 3
3 1
3 2
3 3

PHP foreach loop


The foreach loop is used to traverse the array elements. It works only on array
and object. It will issue an error if you try to use it with the variables of different
datatype. In foreach loop, we don't need to increment the value.

Syntax
foreach ($array as $value) {
//code to be executed
}

Example 1: PHP program to print array elements using foreach loop.


PHP Unit 1 20 GSC BCA

<?php Output:
//declare array
$season = array ("Summer", "Winter", Summer
"Autumn", "Rainy"); Winter
Autumn
//access array elements using foreach loop Rainy
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>

PHP try-catch
PHP try and catch are the blocks with the feature of exception handling, which
contain the code to handle exceptions. They play an important role in exception
handling. There is one more important keyword used with the try-catch block is throw.
The throw is a keyword that is used to throw an exception.
Each try block must have at least one catch block. On the other hand, a try block
can also have multiple catch blocks to handle various classes of exception.

Syntax
The following syntax is used in exception handling to handle runtime errors -

<?php
//try block
try {
//code that can throw exception
}
//catch block
catch (Exception $e) {
//code to print exception caught in the block
}
//finally block
finally {
//any code that will always execute
}
?>

try
The try block contains the code that may contain an exception. An exception
raised in try block during runtime is caught by the catch block. Therefore, each try block
must have at least one catch block. It consists of the block of code in which an exception
can occur.

Following points needs to be noted about the try:


1. The try block must be followed by a catch or finally block.
2. A try block must have at least one catch block.
3. There can be multiple catch blocks with one try block.
PHP Unit 1 21 GSC BCA

catch
The catch block catches the exception raised in the try block. It contains the code
to catch the exception, which is thrown by throw keyword in the try block. The catch
block executes when a specific exception is thrown. PHP looks for the matching catch
block and assigns the exception object to a variable.

Following points to be noted about the catch:

1. There can be more than one catch block with a try.


2. The thrown exception is caught and resolved by one or more catch.
3. The catch block is always used with a try block. It cannot be used alone.
4. It comes just after the try block.

throw
It is a keyword, which is used to throw an exception. Note that one throw at least
has one "catch block" to catch the exception. It lists the exceptions thrown by function,
which cannot be handled by the function itself.

finally
It is a block that contains the essential code of the program to execute. The finally
block is also used for clean-up activity in PHP. It is similar to the catch block, which is
used to handle exception. The only difference is that it always executes whether an
exception is handled or not.
The finally block can be specified after or in place of catch block. It always
executes just after the try and catch block whether an exception has been thrown or not,
and before the normal execution restarts. It is useful in the following scenarios - Closing
of database connection, stream.

Example 1

<?php
//user-defined function with an exception
function checkNumber($num) {
if($num>=1) {
//throw an exception
throw new Exception("Value must be less than 1");
}
return true;
}

//trigger an exception in a "try" block


try {
checkNumber(5);
//If the exception throws, below text will not be display
echo 'If you see this text, the passed value is less than 1';
}

//catch exception
catch (Exception $e) {
PHP Unit 1 22 GSC BCA

echo 'Exception Message: ' .$e->getMessage();


}
finally {
echo '</br> It is finally block, which always executes.';
}
?>

Output:

Exception Message: Value must be less than 1


It is finally block, which always executes.

Declare

The declare keyword sets an execution directive for a block of code. If the declare
statement is not followed by a block then the directive applies to the rest of the code in
the file.
There are three directives which can be declared: ticks, encoding and strict_types.

The structure of a declare statement is:


declare (directive)statement

exit and return


The exit() function prints a message and terminates the current script.

Syntax
exit(message)

Example – Print a message and exit the current script:

<?php
$site = "https://www.w3schools.com/";
fopen($site,"r")
or exit("Unable to connect to $site");
?>

The return statement returns from a function or, at the top level of the program, from
the script.

<?php Output:
function add1($x) { 5 + 1 is 6
return $x + 1;
}
echo "5 + 1 is " .
add1(5);
?>
PHP Unit 1 23 GSC BCA

Goto
The goto operator can be used to jump to another section in the program. The
target point is specified by a case-sensitive label followed by a colon, and the instruction
is given as goto followed by the desired target label.

Example 1

<?php Output:
goto a;
echo 'Foo'; Bar

a:
echo 'Bar';
?>

PHP Include and Require

PHP allows you to include file so that a page content can be reused many times. It is
very helpful to include files when you want to apply the same HTML or PHP code to
multiple pages of a website. There are two ways to include file in PHP.

1. include
2. require

PHP include
PHP include is used to include a file on the basis of given path. You may use a
relative or absolute path of the file.

Syntax
There are two syntaxes available for include:

include 'filename ';


Or
include ('filename');

Example

File: menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>

File: include1.php

<?php include("menu.html"); ?>


<h1>This is Main Page</h1>
Output:
PHP Unit 1 24 GSC BCA

Home |
PHP |
Java |
HTML
This is Main Page

PHP require
PHP require is similar to include, which is also used to include files. The only
difference is that it stops the execution of script if the file is not found whereas include
doesn't.

Syntax
There are two syntaxes available for require:

require 'filename';
Or
require ('filename');

Example

File: menu.html

<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>

File: require1.php

<?php require("menu.html"); ?>


<h1>This is Main Page</h1>

Output:

Home |
PHP |
Java |
HTML
This is Main Page

You might also like