You are on page 1of 17

Unit-1 Introduction to PHP PHP and MYSQL

Unit-1
Introduction to PHP
History, Advantages of PHP, HTML relationship, Interpreting vs. Compiling, Basic syntax of
PHP, Writing and Running PHP scripts, variable types - Local and Global, Superglobal
variable and their scope, Comments, Types of Data, Automatic type conversion, Forcing a
type with type casting, Non-decimal number systems, Pre-set variables, Constants, Pre-set
constants, Operators, unary operators, arithmetic operators, logical operators, conditional
operators, conversion operators, Comparison operators, The Ternary Operator, The scope
resolution operator. Control statements – sequence, Conditional statements, loops, jump
statements.

What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension “.php”

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even
lash movies. You can also output any text, such as XHTML and XML
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 1


Unit-1 Introduction to PHP PHP and MYSQL

PHP originally stood for Personal Home Page, but it now stands for the recursive acronym
PHP: Hypertext Preprocessor. PHP: Hypertext Preprocessor (or simply PHP) is a server-
side scripting language designed for making dynamic and interactive Web pages. The
founder of PHP is Rasmus Lerdorf in 1994.

1. 1 History

 PHP development began in 1994 when Rasmus Lerdorf wrote several Common
Gateway Interface (CGI) programs in C, which he used to maintain his personal
homepage. He extended the work with web forms and to communicate with databases.
This implementation is called "Personal Home Page/Forms Interpreter" or (PHP/FI 1)
version 1.0 in June 8, 1995.
 A development team began to form and, after months of work and beta testing,
officially released PHP/FI 2 in November 1997.
 Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of
PHP 3, changing the language's name to the recursive acronym PHP: Hypertext
Preprocessor. Afterwards, public testing of PHP 3 began, and the official launch came
in June 1998.
 On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released. As of August
2008 this branch reached version 4.4.9. PHP 4 is no longer under development nor will
any security updates be released.
 On July 14, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5
included new features such as object-oriented programming, the PHP Data Objects
(PDO) extension and numerous performance enhancements.
 In 2005, a project headed by Andrei Zmievski was initiated to bring native Unicode
support throughout PHP, by embedding the International Components for Unicode
(ICU) library, and representing text strings as UTF-16 internally. Since this would
cause major changes both to the internals of the language and to user code, it was
planned to release this as PHP 6 of the language, along with other major features then
in development.
 During 2014 and 2015, a new major PHP version was developed, which was numbered
PHP 7. The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next
generation (phpng). PHP 7 included new language features such as, it introduces return
type declarations for functions, which complement the existing parameter type
declarations, and support for the scalar types (integer, float, string, and boolean) in
parameter and return type declarations.

1. 2 Advantages of PHP

 PHP (Hypertext Pre-Processor) is a server-side web programming language that is widely


used for web development
 PHP is dynamic. PHP works in combination of HTML to display dynamic elements on
the page
 PHP is cheap, secure, fast and reliable for developing web applications

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 2


Unit-1 Introduction to PHP PHP and MYSQL

 MySQL is used with PHP as back-end tool. MySQL is the popular online database and
can be interfaced very well with PHP
 PHP can add, delete, modify data in your database
 PHP language has its roots in C and C++. PHP syntax is most similar to C and C++
language syntax. So, programmers find it easy to learn and manipulate
 PHP can run on both UNIX and Windows servers
 PHP can create, open, read, write, delete, and close files on the server
 PHP can be used to send and receive cookies
 PHP can be used with a large number of relational database management systems, runs on
all web servers and is available for many different operating systems
 PHP5 a fully object oriented language and its platform independence and speed on Linux
server helps to build large and complex web applications
 PHP can be used to control user-access
 PHP can used to encrypt data

1.3 HTML Relationship with PHP


HTML is a language used to describe to a browser how to display text and other objects in a
browser window. It is not a programming language. HTML works on a client computer. PHP
is a scripting language, and can be used to create web pages written in HTML. PHP runs on
the server (the system from which the page comes), and is a full-fledged programming
language.

1.4 Interpreting vs. Compiling


A compiler translates the source code of the program into another language format that can
be directly executed by a lower-level machine. This can be an abstract machine. The
translation from source code into lower-level code depends on the abstract syntax and on the
operational semantics of the programming language. An interpreter executes the source code
directly. The interpreter executes the program directly, translating each statement into a
sequence of one or more subroutines, and then into another language.

1.5 Basic syntax of PHP


There are four ways in which we can embedding PHP within HTML. Few methods are
already set by default and Short-open or ASP-style tags we need to change the configuration
of php.ini file. A PHP script can be placed anywhere in the document.
i. Canonical PHP Tags
ii. SGML or Short HTML Tags
iii. HTML Script Tags
iv. ASP Style Tags

i. Canonical PHP Tags: The script starts with <?php and ends with ?> . These tags are
called ‘Canonical PHP tags’. Every PHP command ends with a semi-colon (;).

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 3


Unit-1 Introduction to PHP PHP and MYSQL

<?php
echo "Welcome to PHP.!";
?>

ii. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The
script starts with <? and ends with ?>. This will only work by setting the short_open_tag
setting in php.ini file to ‘on’.
<?
echo "Hello, world!";
?>

iii. HTML Script Tags: HTML Script Tags: These are implemented using script tags. This
syntax is removed in PHP 7.0.0. so its no more used.
<script language="php">
echo "hello world!";
</script>

iv. ASP Style Tags: To use this we need to set the configuration of php.ini file. These are
used by Active Server Pages to describe code blocks. These starts with <% and ends with
%>.
Example:
<%
echo "hello world";
%>

1.7 Variables and Its Scope


Variables is a valid identifier which are used to store the values or data that can be used later
in a program. There are few rules, that needs to be followed and facts that need to be kept in
mind while dealing with variables in PHP:
 Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short names
(like $n or $f or $x)
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
 A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’,
‘A-Z’, ‘0-9 and ‘_’) in their name.
 Any variable names in PHP names must start with a letter or underscore and no numbers.
 PHP is a loosely typed language and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values.

1.7.1 Variable Scopes

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 4


Unit-1 Introduction to PHP PHP and MYSQL

Scope of a variable is defined as its extent in program within which it can be accessed Or the
scope of a variable is the portion of the program with in which it is visible or can be accessed.
Depending on the scopes, PHP has three variable scopes:
i. Local variables
ii. Global variables
iii. Static variables
i. Local variables: The variables declared within a function are called local variables to that
function and has its scope only in that particular function. Any declaration of a variable
outside the function with same name as that of the one within the function is a complete
different variable.
Example:
<?php
$num = 60;
function local_var()
{
$num = 50; echo "local num = $num";
echo “<br>”;
}
local_var();
echo "Variable num outside local_var() is $num ";
?>
Output: local num = 50
Variable num outside local_var() is 60
ii. Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function
we need to use the “global” keyword before the variable to refer to the global variable.
Example:
<?php
$num = 20;
function global_var()
{
global $num; echo "Variable num inside function : $num ";
echo “<br>”;

}
global_var(); echo "Variable num outside function : $num";
echo “<br>”;
?>
Output: Variable num inside function : 20
Variable num outside function : 20

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 5


Unit-1 Introduction to PHP PHP and MYSQL

iii. Static variable: To store the variables even after the completion of function execution, a
Static variable is able to retain its value between different function calls. The static variable is
only initialized once, if it is not initialized, then it is automatically initialized to 0. Example:
<?php
function static_var()
{ Output:
static $num ; 1
$sum = 7; 8
2
$sum++;
8
$num++;
echo $num;
echo “<br>”;
echo $sum;
echo “<br>”;
}
static_var();
static_var();
?>
1.8 Superglobal variables or Pre-set or Pre-defined variable
The Superglobal variables are specially-defined array variables in PHP that make it easy to
store and get information from one page to another in an application. These variables can be
accessed from any function, class or any file without declaring any global variable. The list of
superglobal variables available in PHP are
i. $GLOBALS
ii. $_SERVER
iii. $_REQUEST
iv. $_GET
v. $_POST
vi. $_SESSION
vii. $_COOKIE
viii. $_FILES
ix. $_ENV
i. $GLOBALS: It is a superglobal variable which is used to access global variables from
anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[index].
The index holds the name of the variable.
<?php
$x = 30;
$y = 20;
function multiplication()
{
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 6


Unit-1 Introduction to PHP PHP and MYSQL

}
multiplication();
echo $z;
?>

ii. $_SERVER: It is a PHP super global variable that stores the information about headers,
paths and script locations.
<?php /serverglobal.php
localhost
echo $_SERVER['PHP_SELF']; echo "<br>"; localhost
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
echo $_SERVER['SERVER_NAME']; like Gecko) Chrome/67.0.3396.87 Safari/537.36
echo "<br>"; /serverglobal.php

echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT']; echo "<br>";
echo $_SERVER['SCRIPT_NAME']; echo "<br>"
?>

iii. $_REQUEST: It is a superglobal variable which is used to collect the data after
submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET
perform the same task and are widely used.

iv. $_GET: $_GET is a super global variable used to collect data from the HTML form after
submitting it. When form uses method get to transfer data, the data is visible in the query
string, therefore the values are not hidden. $_GET super global array variable stores the
values that come in the URL.

v. $_POST: It is a super global variable used to collect data from the HTML form after
submitting it. When form uses method post to transfer data, the data is not visible in the query
string, because of which security levels are maintained in this method.

vi. $_COOKIE: It is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page with a browser,
it will send the cookie too. With PHP, you can both create and retrieve cookie values.

vii. $_SESSION: A session is a way to store information (username, favorite color) to be


used across multiple pages. By default, session variables last until the user closes the
browser.

1.9 Data Types


Data type defines the type of data a variable can store. PHP allows eight different types of
data types. All of them are discussed below. The first five are called simple data types and the
last three are compound data types:

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 7


Unit-1 Introduction to PHP PHP and MYSQL

i. Integer
ii. Double
iii. String
iv. NULL
v. Boolean
vi. Array
vii. Resource
viii. Object
i. Integer: Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point. They can be decimal (base 10), octal (base
8) or hexadecimal (base 16). The default base is decimal (base 10). The octal integers can be
declared with leading 0 and the hexadecimal can be declared with leading 0x. The range of
integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50; $deci2 = 654;
// octal base integers
$octal1 = 07;
// hexadecimal base integers
$octal = 0x45; $sum = $deci1 + $deci2;
echo $sum;
?>
ii. Double: Can hold numbers containing fractional or decimal part including positive and
negative numbers. By default, the variables add a minimum number of decimal places.
Example:
<?php
$val1 = 50.85; $val2 = 654.26;
$sum = $val1 + $val2; echo $sum;
?>

iii. String: Hold letters or any alphabets, even numbers are included. These are written within
double quotes during declaration. The strings can also be written within single quotes but it
will be treated differently while printing variables. To clarify this look at the example below.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name';
?>
The name of the Geek is Krishna
The name of the geek is $name

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 8


Unit-1 Introduction to PHP PHP and MYSQL

iv. NULL: These are special types of variables that can hold only one value i.e., NULL. We
follow the convention of writing it in capital form, but its case sensitive.

v. Boolean: Hold only two values, either TRUE or FALSE. Successful events will return true
and unsuccessful events return false. NULL type values are also treated as false in Boolean.
Apart from NULL, 0 is also consider as false in boolean. If a string is empty then it is also
considered as false in boolean data type.

vi. Arrays: Array is a compound data-type which can store multiple values of same data type.
Below is an example of array of integers.
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
vii. Objects: Objects are defined as instances of user defined classes that can hold both values
and functions.

viii. Resources: Resources in PHP are not an exact data type. These are basically used to
store references to some function call or to external PHP resources. For example, consider a
database call. This is an external resource.

1.10 Automatic Type Conversion


PHP provides several functions that can be used to convert a value to a specific type.
 strval() function can be used to convert a value to a string,
 intval() function can be used to convert a value to a integers,
 floatval() function can be used to convert a value to a floating point numbers,
 boolval() function can be used to convert a value to a boolean,
 var_dump () displays structured information about one or more expressions that includes
its type and value.
<?php
$val = 88; // integer
// pass $val to strval and check return value with var_dump
var_dump( strval($val) ); // string(2) "88"
// check type and value of $val
var_dump($val); // int(88)
?>

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 9


Unit-1 Introduction to PHP PHP and MYSQL

1.10 Constants
Constants are identifiers that can be assigned any fixed values. They remain constant
throughout the program and cannot be altered during execution.
 By default, a constant is always case-sensitive, unless mentioned
 A constant name must never start with a number
 It always starts with a letter or underscores, followed by letter, numbers or underscore.
 It should not contain any special characters except underscore
 By default, constants are automatically global, and can be used throughout the script,
accessible inside and outside of any function.

Creating a PHP Constant : The define() function in PHP is used to create a constant as
shown below:
Syntax: define(name, value, case_insensitive)
Where, name: The name of the constant.
value: The value to be stored in the constant.
case_insensitive: Defines whether a constant is case insensitive. By default this value is
False, i.e., case sensitive.
Example:
<?php
// This creates a case-sensitive constant
define("VVFGC", "Vidyavahini First Grade College"); echo VVFGC,
"\n";
// This creates a case-insensitive constant
define("VVFGC", " Vidyavahini First Grade College ", true); echo hello;
?>

constant() function: Instead of using the echo statement, there is an another way to print
constants using the constant() function.
Syntax: constant(name)
Example:
<?php
define("VVFGC", "Vidyavahini First Grade College");
echo VVFGC, "\n";
echo constant("VVFGC"); // same as previous
?>

1.10 Operators
Operators are nothing but symbols needed to perform operations on operands. Thus, PHP
provides us with many operators to perform operations on various operands or variables or
values. Given below are the various groups of operators:
 Arithmetic Operators
 Logical Operators

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 10


Unit-1 Introduction to PHP PHP and MYSQL

 Relational Operators
 Bitwise Operators
 Assignment Operators
 Increment/Decrement Operators
 Conditional or Ternary Operators
 Array Operators
 String Operators
 Spaceship Operators

1.10.1 Arithmetic Operators: The arithmetic operators are used to perform simple
mathematical operations like addition, subtraction, multiplication etc. Below is the list of
arithmetic operators along with their syntax and operations that PHP provides us:
Operator Name Syntax Operation
+ Addition $x + $y Sum the operands
- Subtraction $x – $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y Quotient of the operands
** Exponentiation $x ** $y $x raised to the power $y
% Modulus $x % $y Remainder of the operands

1.10.2 Logical Operators: These are basically used to operate with conditional statements
and expressions. Also, a condition can either be met or cannot be met so the result of a
conditional statement can either be true or false.
Operator Name Syntax Operation
and Logical AND $x and $y True if both the operands are true else false
or Logical OR $x or $y True if either of the operand is true else false
xor Logical XOR $x xor $y True if either of the operand is true and false
if both are true or false
&& Logical AND $x && $y True if both the operands are true else false
|| Logical OR $x || $y True if either of the operand is true else false
! Logical NOT !$x True if $x is false

1.10.3 Relational Operators: These operators are used to compare two elements and outputs
the result in Boolean form.
Operator Name Syntax Operation
== Equal To $x == $y Returns True if both the operands are equal
!= Not Equal To $x != $y Returns True if both the operands are not equal
<> Not Equal To $x != $y Returns True if both the operands are unequal
=== Identical $x === $y Returns True if both the operands are equal
and are of the same type
!== Not Identical $x == $y Returns True if both the operands are unequal
and are of different types
< Less Than $x < $y Returns True if $x is less than $y
> Greater Than $x > $y Returns True if $x is greater than $y
<= Less Than or $x <= $y Returns True if $x is less than or equal to $y

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 11


Unit-1 Introduction to PHP PHP and MYSQL

Equal To
>= Greater Than $x >= $y Returns True if $x is greater than or equal to
or Equal To $y

1.10.4 Relational Operators: The Bitwise operators is used to perform bit-level operations on
the operands. The operators are first converted to bit-level and then calculation is performed
on the operands.
Operator Name Syntax Operation
& Bitwise AND $x& $y The result of AND is 1 only if both bits are 1.
| (Bitwise OR) $x | $y The result of OR is 1 any of the two bits is 1
^ Bitwise XOR The result of XOR is 1 if the two bits are different
~ Bitwise NOT ~$x Bitwise NOT operator takes one number and inverts all
bits of it.
<< Bitwise Left Shift $x << $y This will shift the bits of $x towards the left. $y decides
the number of time the bits will be shifted
>> Bitwise Right Shift $x >> $y This will shift the bits of $x towards the right. $y
decides the number of time the bits will be shifted.

1.10.5 Assignment Operators: These operators are used to assign values to different
variable, with or without mid-operations.
Operator Name Syntax Operation
= Assign $x = $y Operand on the left obtains the value of
the operand on right
+= Add then Assign $x += $y Simple Addition same as $x = $x + $y
-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y
*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
/= Divide then Assign $x /= $y Simple division same as $x = $x / $y
(quotient)
%= Divide then Assign $x %= $y Simple division same as $x = $x % $y
(remainder)

1.10.6 Increment/Decrement Operators: These are called the unary operators as it work on
single operands. These are used to increment or decrement values.
Operator Name Syntax Operation
++ Pre-Increment $x++ First returns $x, then increment it by one
-- Pre-Decrement $x– First returns $x, then decrement it by one
++ Post-Increment ++$x First increments $x by one, then return $x
-- Post-Decrement –$x First decrements $x by one, then return $x

1.10.7 Conditional or Ternary Operators: These operators are used to compare two values
and take either of the result simultaneously, depending on whether the outcome is TRUE or
FALSE. These are also used as shorthand notation for if…else statement
Syntax:
$var = (condition)? value1 : value2;

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 12


Unit-1 Introduction to PHP PHP and MYSQL

Here, condition will either evaluate to true or false. If the condition evaluates to True, then
value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

1.10.8 Array Operators: These operators are used in case of arrays.


Operator Name Syntax Operation
+ Union $x + $y Union of both i.e., $x and $y
== Equality $x == $y Returns true if both has same key-value pair
!= Inequality $x != $y Returs True if both are unequal
=== Identity $x === $y Returns True if both has same key-value pair in
the same order and of same type
!== Non-Identity $x !== $y Returns True if both are not identical to each other
<> Inequality $x <> $y Returns True if both are unequal

1.10.9 String Operators: These are implemented over strings.


Operator Name Syntax Operation
. Concatenation $x.$y Concatenated $x and $y
.= Concatenation and assignment $x.=$y First concatenates then assigns, same as $x = $x.$y

1.10.10 Spaceship Operators: PHP 7 has introduced a new kind of operator called spaceship
operator (). These operators are used to compare values but instead of returning boolean
result, it returns integer values. If both the operands are equal, it returns 0. If the right
operand is greater, it returns -1. If the left operand is greater, it returns 1.
Operator Syntax Operation
$x < $y $x <=> $y Identical to -1 (right is greater)
$x > $y $x <=> $y Identical to 1 (left is greater)
$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)
$x == $y $x <=> $y Identical to 0 (both are equal)
$x != $y $x <=> $y Not Identical to 0

1.11 Decision making statements


PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. PHP provides us with four conditional statements:
 if statement
 if…else statement
 if…elseif…else statement
 switch statement

if Statement: This statement allows us to set a condition. On being TRUE, the following
block of code enclosed within the if clause will be executed.
Syntax :
if (condition)
{

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 13


Unit-1 Introduction to PHP PHP and MYSQL

// if TRUE then execute this code


}

if…else Statement: If a condition is TRUE then if block gets executed, otherwise else block
gets executed.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
if…elseif…else Statement: This allows us to use multiple if…else statments. We use this
when there are multiple conditions of TRUE cases.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}

switch Statement: The “switch” performs in various cases i.e., it has various cases to which it
matches the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same
case is executed.
Syntax:
switch(n)
{
case statement1:
code to be executed if n==statement1;

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 14


Unit-1 Introduction to PHP PHP and MYSQL

break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default: code to be executed if n != any case;
}

Flowcharts:

if condition if-else condition

else if ladder condition switch case

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 15


Unit-1 Introduction to PHP PHP and MYSQL

1.12 Looping statements: Like any other language, loop in PHP is used to execute a
statement or a block of statements, multiple times until and unless a specific condition is met.
PHP supports four types of looping techniques
 for loop
 while loop
 do-while loop
 foreach loop
for loop: This type of loops is used when the user knows in advance, how many times the
block needs to execute. These type of loops are also known as entry-controlled loops. There
are three main parameters to the code, namely the initialization, the test condition and the
counter.
Syntax:
for (initialization expression; test condition; update expression)
{
// code to be executed
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to
some value, then check whether this variable is less than or greater than counter value. If
statement is true, then loop body is executed and loop variable gets updated. Steps are
repeated till exit condition comes.

while loop: The while loop is also an entry control loop like for loops i.e., it first checks the
condition at the start of the loop and if its true then it enters the loop and executes the block
of statements, and goes on executing it as long as the condition holds true.
Syntax:
while (if the condition is true)
{
// code is executed
}

do-while loop: This is an exit control loop which means that it first enters the loop, executes
the statements, and then checks the condition. Therefore, a statement is executed at least once
on using the do…while loop. After executing once, the program is executed as long as the
condition holds true.
Syntax:
do
{
//code is executed
} while (if condition is true);

foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax:

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 16


Unit-1 Introduction to PHP PHP and MYSQL

foreach (array_element as value)


{
//code to be executed
}
Example:
<?php
$arr = array (5, 8, 30, 1, 3, 6);
foreach ($arr as $val)
{
for ($i=1;$i<&val;$i++)
{
echo "*";
}
echo “<br>”
}
echo “Bye!!”; for -loop
?>

do-while while

Irfan Ahmed., Asst. Professor., Dept. of BCA., SSCASCW, Tumkur 17

You might also like