Professional Documents
Culture Documents
Cca61 Oss
Cca61 Oss
Cca61 Oss
moolify ard
Putlicly acesile ’angone (an Aee,
Advantaqes af oss:
>Fledtsüty and oqtt
2> Speed
3 cOst- Efe ctivereks
V4 4S AbiUty to stelt Srmcl
S All PAcqkams ale fee b use
oSS teh-PHP IYSSL)Apache and css/Tavoserfpt poti2
leoks atke web Pago
handles dl the Manaq es ael
tu data,
web Selve
Duna'e
9 web contenti bHeb,ath content that tonstntty ou
egulacly change, kasod on use nteactions, tmng g otheu
Plasneees that dekiine what content s detv eed to tu
s e tet, audio, videe, tormab,outuhe, fhTeitle, gpoe
Eq <head
<seript Src"htps: |)ajox. gege apis -(cnlajox|lHbs/jqueuy/
Anhepd,todJAs
chocty style"text -Lgni tentu' td bedy'"
,9pochiEnteu you colas choite cikis
<button bype ="button' onclk"chargecelotoS 3
Colod
</buttons
</ scipt
cleat etele or polty of cob
ciaoe
aYc)->Method wed o
Mettod to aetuell dawte ale oD thu courva
<boke) ’
ce-;rewioht
el'ssto e e: He;
rM15Audio Toq is Ukedl to define Sourds Seh as vst
ucio clps. Thele ade s Apreuted le fenat
and othel
HTMLS cudio tag
A mp3 2 Wav 3 C1g.
Eg audio contio lss
aucio/mfg
</auoio
Attutbutes d HrLsAudio Taq' diples
itt de~ires thi oudio tonti os hek
hih t drlaed
Contioh
wtth pleylruse utons . tlaut lana
flayng
that the cudde uko
2> cuuteplay- it gpecites
thot the oudio fle widstaiblegai
D SFecites
vely bime
4 mutedit i wied to mute
the autto view to yploode
S pleloodit sreifes
when a Foge loods
oside
Eq <heod
Beod ection heinky exteiaJ' ¢
elernent qoes '
CIbed Seheet tyre"'ktleet"
<lheody
Eq't rryty le.csss
mystye. css
An enteral s s
tie hotd not 'torte witen o n
The sle rust Be contain any htd
colal iqhthses thlpety yele
ololi rovy; ralgin--ledt :20 pr 2opx
cut */. Commert
Comment ard enoly
A CSS
olor Yed
J*This is asinqle-tine cornrert */
test-aqr! Centel)
stylestheods
HellO
Sq'- <Styles
" lente
tet-olrni Lelt i
Srallee
<lbty
Stule Sheet Popeties. Tt % csed fos bockgrnd eet.
y Packqourd- cotot: booys bqrolot: hbocaye;
Bq-hage , boolybg- irnage iur) (";rogejrq
iS bg-nage;UCimage. pra
i>B repeat ihooly repeat- x) -ahpwirel
b-Yefeati
(ss Text:
Text colok: The color Popeity
ften
ve
pectreo
t
byi
rpr
wsth css,a colo s rOst
> HEx Vue- like ff0opn
’RGB Vaure - (ike qb
rgb(265, ,o)
>colo rome-like yed"
q'bocly!
toloX! uej
3.
Celos :vglQsS.ODi
Toct Algbment! 7he toct-align popeety s ket h
how ontoJ agrment dq Text co be centeledn n
justr) ed,hen ta%
cLlined to toe et
Ctched s
tct evceyline
ight màlgfnsiaie Sbaight.
has ead widt% cnd lelt
toct-align! (ente;
text- aligr:righti
text-aligh:jes ityi
3Tet -Decokctron: The tert-deoAattor prcfetyS LAeo o
Set or erore detorcton fom f t . ie ext-dewstO
221
or desrn puore .
cq!<style 5D,22) y
text-aio: Cente.;
tctdeoration! uroetine;
o/P id
teoxt decorator: Gne-thuaughi This surdetln o
text-deovatien: Overine Ths s overineholb)
towetcLse hettees tn o teit.
p.uprer taef
texkfndent :Fopx}
toce
eolo Fomati for f D, GreEE
fosmat:RoB fom at isth shoxt
s RGB defning e colee a/7NL
BLDE ttt wsed tou iclues AR Gr. Bthat aue ange an
by speitying the he co
SImply afreste inlttnnels coleie
g55. Th: Pefely is i
oto ty clng e g60 peopety.
goitied
lalues tnthis teuat cue
2> RGBA FoArat:
contains ACeIphothat tef speafes th
that Roe4
tharutcuenuy efelenent's. The yalue of alpho is in the
Yange o.0 to Io
tanpobt aspuent
<Syles
tect- cltn'centel ;
3T.2 1
Coe:
thsltf
Coseeen
hecyhtmdsavloo
UN:T-2
PaaONY-bcwe os.T is not Jue Umi!
ANDX Q:nur UNIX-bose
platto mto
Selvels,'s embedd ed Sytters The Keenel
Aun desktops,
seheoliuing
manage vaiwus Sotvice Soch as pocess
ricatern cheduling, basic eiphetal deuttes ,
fle and mle
Advantges
hauiney aecyeroning Knaledg e coun cwterni2 e th os
Dne con Conbi bub ,moct, libitub 5 enhounte thu teole
fr ary puupure
2y ecutyalinuk Be eurily fecttey s thr rein teasbn
táat 1t fs the most fvertHe optien
ot conpletcly ofebut TE less forcevelopels .TE S
vunelable thon ot
PE is dree touue I is disbibuted
Dnalee GNU
ALghteeqhtThe Yeqilernents tor vernnd ris
mvch less thon odher OS. ineXa
itieernoy footp
oY Slewdcun.Tt has
bre-ep- tirnes.
LpeldprOnte noX ystem provides hrh perforqcunee
~ cd dekfor/
movetle
Gre nedir
tocroer
abecSC Sfa ee
oNl
$ f : or checeino
set SySte
, Sdabe : osed to sO Culent cote (o)
14date
doele
Mach ,
hosérane sed to view thu ourno the host
hostrome
1shostanoi: dedo shos If adoresS.
s ran:0sel to readnore detaU about Cornmad.
man qrep
Kene)
ser, )A
ede: xeution one n behal od c
USel mcole!
us rdu Uhet le
Useiflo(ey bitO
Se(steyo DselmOle lrocdla
reut c
C
Kene (bit e)
Hle sytem tonceftt ha ctuyctuee
hke sovctue also relfeied to os tte DiLtery trae
tolthe s a bcutEN that CtoeAmuttiele ie
2bot
binaydr oPtion
t
Jed is
Meuoe lEs Cembina ong, fttition wrh
dowice.
dev
boot ete irt
DIsk
titono Patiton)-faltene
lutenn
ets Tt Ts Atarcs for thid extended e ysteny
Srom Lire Kelnel 2.4./5 ts as ausibs.
Statrg
The rzaio bereft f et Ts: Joulnaling
suster Se car be kon 2
2TB. ovelal et fe
32T8.redue fle torupén. itisae 3 coun
276 to
casiy Yecovel d
bd
et4: Tt Slards fon fouth ectended ile Syben,Nocmu
slaing
fom inuL keinel 2.6q etq eas ueiaile.
foolividuo fle iZeleon be tlom lbCB to bTB
ovelal eoe exto fAle syster sze s 1£B (oa bytJ.ta
IEB = lo24 PB CPetbyt). PB to24 TB (Jelaby).
D)lectoly con Contain o ro of b, coo subAetoie
File System
Sector Jaunal Bloc o loK
glock
Souna
Tansaoton Dote or oto
Begir Blbc 123Block forTrunsaticd
bs-er Trnsa chod pot do
Begín2 elok lw24id
1
Block
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in
the same category as C and C++.
JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content
of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser.
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.
JAVASCRIPT & MYSQL
JavaScript Variables
Variables are "containers" for storing information.
A variable can have a short name, like x, or a more descriptive name, like carname.
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
Example
A variable's value can change during the execution of a script. You can refer to a variable by its name to
display or change its value.
<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>
</body>
</html>
Output :
Welcome
XYZ
The script above declares a variable, assigns a value to it, displays the value, change the value, and
displays the value again.
JAVASCRIPT & MYSQL
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Scorpio";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Scorpio.
Note: When you assign a text value to a variable, use quotes around the value.
If you assign values to variables that have not yet been declared, the variables will automatically be
declared.
These statements:
x=5;
carname="Scorpio";
var x=5;
var carname="Scorpio";
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
JAVASCRIPT & MYSQL
After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.
DataTypes
Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.
Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string
literally; it doesn't process it. You'll use strings for text you want displayed or values you want
passed along.
Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.
Data Types
TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Null A special keyword for exactly that – the null value (that is, nothing)
JAVASCRIPT & MYSQL
JavaScript Arithmetic
y=x-5;
z=y+5;
JavaScript Operators
The operator = is used to assign values.
y=5;
z=2;
x=y+z;
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Given that x=10 and y=5, the table below explains the assignment operators:
The + operator can also be used to add string variables or text values together.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
JAVASCRIPT & MYSQL
After the execution of the statements above, the variable txt3 contains "What a verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Comparison and Logical operators are used to test for true or false.
JAVASCRIPT & MYSQL
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables
or values.
Given that x=5, the table below explains the comparison operators:
Comparison operators can be used in conditional statements to compare values and take action depending
on the result:
You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
JAVASCRIPT & MYSQL
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value
"Dear President " else it will be assigned "Dear".
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.
if statement - use this statement if you want to execute some code only if a specified condition is
true
if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
if...else if.... else statement - use this statement if you want to select one of many blocks of code to
be executed
switch statement - use this statement if you want to select one of many blocks of code to be
executed
If Statement
You should use the if statement if you want to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!
Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
JAVASCRIPT & MYSQL
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();
if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
</script>
Note: When comparing variables you must always use two equals signs next to each other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the
specified condition is true.
If...else Statement
If you want to execute some code if a condition is true and another code if the condition is not true, use
the if ...else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
JAVASCRIPT & MYSQL
You should use the if....else if...else statement if you want to select one of many sets of lines to execute.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
JAVASCRIPT & MYSQL
{
document.write("<b>Hello World!</b>");
}
</script>
You should use the switch statement if you want to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}
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.
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
JAVASCRIPT & MYSQL
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.
JavaScript Loops
Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
JAVASCRIPT & MYSQL
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.
The while loop is used when you want the loop to execute and continue executing while the specified
condition is true.
while (var<=endvalue)
{
code to be executed
}
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html>
JAVASCRIPT & MYSQL
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE,
and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the condition is
tested.
do
{
code to be executed
}
while (var<=endvalue);
Example
<html>
<body>
<script type="text/javascript">
JAVASCRIPT Notes
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>
Result
The number is 0
There are two special statements that can be used inside loops: break and continue.
Break
The break command will break the loop and continue executing the code that follows after the loop (if
any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
JAVASCRIPT& MYSQL
Notes
</html>
Result
The number is 0
The number is 1
The number is 2
Continue
The continue command will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
JAVASCRIPT& MYSQL
Notes
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database , information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.
The create database Statement
The general syntax is as follows:
create database database_name
From the MySQL command-line client, you can simply type in the following command:
mysql> create database my_database;
Example:
create table topics ( topic_id integer not null auto_increment, parent_id integer default 0 not
null, root_id integer default 0, name varchar(255), description text null, create_dt timestamp,
modify_dt timestamp, author varchar(255) null, author_host varchar(255) null, primary
key(topic_id), index my_index(parent_id) )type=myisam;
Text strings must be surrounded by single quote marks (‘), or double-quote marks (‘’) if you’re
not running in ANSI mode.
For example:
insert into table_name (text_col, int_col) values (‘hello world’, 1)
The update Statement
update table_name set col_1=value1, col_2=value_2 where col=value
For Example:
update folks set fname=’Vito’ where id=2;
The delete Statement
The delete statement removes a row or multiple rows from a table.
The syntax is as follows:
delete from table_where where-clause
For Example:
delete from folks where id=1;
The Basic select Statement
select column_1, column_2, column_3 from table_name
Or
select * from table_name
The where clause
The where clause limits the rows that are returned from your query.
select * from users where userid = 2;
JAVASCRIPT& MYSQL
Notes
For Example:
IntroductiontoPHP&Features
PHPisawidely-used,free,andefficientalternativetocompetitorssuchasMicrosoft'sASP.
Example
<html>
<body>
<?php
echo"MyfirstPHP
script!"; ?>
</body>
</html>
WhatYouShouldAlreadyKnow
Beforeyoucontinueyoushouldhaveabasicunderstandingofthefollowing:
• HTML
• CSS
• JavaScript
WhatisPHP?
• PHPisanacronymfor"PHP:HypertextPreprocessor"
• PHPisawidely-used,opensourcescriptinglanguage
• PHPscriptsareexecutedontheserver
• PHPisfreetodownloadanduse
WhatisaPHPFile?
• PHPfilescancontaintext,HTML,CSS,JavaScript,andPHPcode
• PHPcodeareexecutedontheserver,andtheresultisreturnedtothebrowser as plain
HTML
• PHPfileshaveextension".php"
WhatCanPHP Do?
• PHPcangeneratedynamicpagecontent
• PHPcancreate,open,read,write,delete,andclosefilesontheserver
• PHPcancollectformdata
• PHPcansendandreceivecookies
• PHPcanadd,delete,modifydatainyourdatabase
• PHPcanbeusedtocontroluser-access
• PHPcanencryptdata
WithPHPyouarenotlimitedtooutputHTML.Youcanoutputimages,PDFfiles,and even
Flash movies. You can also output any text, such as XHTML and XML.
WhyPHP?
• PHPrunsonvariousplatforms(Windows,Linux,Unix,MacOSX,etc.)
• PHPiscompatiblewithalmostallserversusedtoday(Apache,IIS,etc.)
• PHPsupportsawiderangeofdatabases
• PHPisfree.DownloaditfromtheofficialPHPresource:www.php.net
• PHPiseasytolearnandrunsefficientlyontheserverside
TostartusingPHP, youcan:
• FindawebhostwithPHPandMySQLsupport
• InstallawebserveronyourownPC,andtheninstallPHPandMySQL
UseaWebHostwithPHP Support
• IfyourserverhasactivatedsupportforPHPyoudonotneedtodoanything.
• Justcreatesome.phpfiles,placetheminyourwebdirectory,andtheserverwill
automatically parse them for you.
• Youdonotneedtocompileanythingorinstallanyextratools.
• BecausePHPisfree,mostwebhostsofferPHPsupport.
• SetUpPHPonYourOwnPC
However,ifyourserverdoesnotsupportPHP, youmust:
PHP Scripts
BasicPHPSyntax
• APHPscriptcanbeplacedanywhereinthedocument.
• APHPscriptstartswith <?phpandendswith?>:
<?php
//PHPcodegoes here
?>
Example
<html>
<body>
<h1>MyfirstPHP page</h1>
<?php
echo"HelloWorld!";
?>
</body>
</html>
• PHPstatementsendwithasemicolon(;)
CommentsinPHP
Commentscanbeusedto:
• Letothersunderstandwhatyouaredoing
• Remind yourself of what you did - Most programmers have experienced coming
back to their own work a year or two later and having to re-figure out what they
did. Comments can remind you of what you were thinking when you wrote the
code
Example
<html>
<body>
<?php
//Thisisasingle-linecomment
#Thisisalsoasingle-line comment
/*
Thisisamultiple-linescomment
block that spans over multiple
lines
*/
//Youcanalsousecommentstoleaveoutpartsofacodeline
$x=5/*+15*/+5; echo
$x;?>
</body>
</html>
Example
<html>
<body>
<?php
ECHO"HelloWorld!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
In the example below, only the first statement will display the value of the $color
variable(thisisbecause$color,$COLOR,and$coLORaretreatedasthreedifferent
variables):
Example
<html>
<body>
<?php
$color="red";
echo"Mycaris".$color."<br>";
echo "My house is ". $COLOR .
"<br>";echo"Myboatis".$coLOR.
"<br>"; ?>
</body>
</html>
DataTypes
• Variablescanstoredataofdifferent types,anddifferentdatatypescando
different things.
PHPsupportsthefollowingdata types:
• String
• Integer
• Float(floatingpointnumbers-alsocalleddouble)
• Boolean
• Array
• Object
• NULL
• Resource
PHPString
• Astringisasequenceofcharacters,like"Helloworld!".
• Astringcanbeanytextinsidequotes.Youcanusesingleordoublequotes:
Example
<html>
<body>
<?php
$x="Hello world!";
$y='Helloworld!';
echo $x;
echo"<br>";
echo $y;
?>
</body>
</html>
OUTPUT:
Helloworld!
Helloworld!
String Functions
• GetTheLengthof aString
• ThePHPstrlen()functionreturnsthelengthofastring.
• Theexamplebelowreturnsthelengthofthestring"Helloworld!":
Example
<html>
<body>
<?php
echostrlen("Hello
world!"); ?>
</body>
</html>
OUPUT:
12
CountTheNumberofWordsinaString
ThePHPstr_word_count()functioncountsthenumberofwordsinastring:
Example
<html>
<body>
<?php
echostr_word_count("Helloworld!");
?>
</body>
</html>
OUPUT:
ReverseaString
• ThePHPstrrev()functionreversesastring:
Example
<html>
<body>
<?php
echostrrev("Helloworld!");
?>
</body>
</html>
OUTPUT:
!dlrowolleH
SearchForaSpecificTextWithina String
• ThePHPstrpos()functionsearchesforaspecifictextwithinastring.
• Ifamatchisfound,thefunctionreturnsthecharacterpositionofthefirstmatch.If no
match is found, it will return FALSE.
• Theexamplebelowsearchesforthe text"world"inthestring"Helloworld!":
Example
<html>
<body>
<?php
echostrpos("Helloworld!","world");
?>
</body>
</html>
OUPUT:
ReplaceTextWithina String
•ThePHPstr_replace()functionreplacessomecharacterswithsomeother
characters in a string.
• Theexamplebelowreplacesthetext"world"with"Dolly":
Example
<html>
<body>
<?php
echostr_replace("world","Dolly","Helloworld!");
?>
</body>
</html>
OUPUT:
HelloDolly!
PHPInteger
Rulesforintegers:
• Anintegermusthaveatleastonedigit
• Anintegermustnothaveadecimal point
• Anintegercanbeeitherpositiveor negative
• Integerscanbespecifiedinthreeformats:decimal(10-based),hexadecimal(16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)
• Inthefollowingexample$xisaninteger.ThePHPvar_dump()function
returns the data type and value:
Example
<html>
<body>
<?php
$x= 5985;
var_dump($x);
?>
</body>
</html>
OUTPUT:
int(5985)
PHPFloat
• Afloat(floatingpointnumber)isanumberwithadecimalpointora numberin
exponential form.
• Inthefollowingexample$xisafloat.The PHPvar_dump()functionreturnsthe data
type and value:
Example
<html>
<body>
<?php
$x= 10.365;
var_dump($x);
?>
</body>
</html>
OUTPUT:
float(10.365)
PHPBoolean
ABooleanrepresentstwopossiblestates:TRUEorFALSE.
$x= true;
$y= false;
Booleansareoftenusedinconditionaltesting.Youwilllearnmoreaboutconditional testing in
a later chapter of this tutorial.
PHP Array
• Anarraystoresmultiplevaluesinonesinglevariable:
• Anarrayisaspecialvariable,whichcanholdmorethanonevalue atatime.
• Ifyouhavealistofitems(alistofcarnames,forexample),storingthecars in single
variables could look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
• However,whatifyouwanttoloopthroughthecarsandfindaspecificone? And
what if you had not 3 cars, but 300?
• Thesolutionistocreateanarray!
• Anarraycanholdmanyvaluesunderasinglename,andyoucanaccessthe values
by referring to an index number.
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0]. ",".$cars[1] ." and".$cars[2].".";
?>
</body>
</html>
OUTPUT:
IlikeVolvo,BMWandToyota.
CreateanArrayin PHP
• InPHP,the array()functionisusedtocreateanarray:
array();
InPHP,therearethreetypesofarrays:
• Indexedarrays-Arrayswithanumericindex
• Associativearrays-Arrayswithnamedkeys
• Multidimensionalarrays -Arrayscontainingoneormorearrays
Variables
• Variablesare"containers"forstoringinformation.
• Creating(Declaring)PHPVariables
• InPHP,avariablestartswiththe$sign,followedbythenameofthevariable:
Example
<html>
<body>
<?php
$txt="Helloworld!";
$x=5; Output:
$y=10.5;
Helloworld!
echo$txt; 5
echo"<br>"; 10.5
echo$x;
echo"<br>";
echo$y;
?>
</body>
</html>
After the execution of the statements above, the variable $txt will hold the value Hello
world!,thevariable $xwillholdthevalue 5,andthevariable$ywillholdthevalue 10.5.
Note:Whenyouassignatextvaluetoavariable,putquotesaroundthe value.
Note:Unlikeotherprogramminglanguages,PHPhasnocommandfordeclaringa variable. It
is created the moment you first assign a value to it.
RulesforPHPvariables:
Avariablecanhaveashortname(likexandy)oramoredescriptivename(age, carname,
total_volume).
• Avariablestartswiththe$sign,followedbythenameofthevariable
• Avariablenamemuststartwithaletterortheunderscorecharacter
• Avariablenamecannotstartwitha number
• Avariablenamecanonlycontainalpha-numericcharactersandunderscores(A- z, 0-
9, and _ )
• Variablenamesarecase-sensitive($ageand$AGEaretwodifferentvariables)
Output Variables
• ThePHPechostatementisoftenusedtooutputdatatothescreen.
Thefollowingexamplewillshowhowtooutputtextanda variable:
Example
<html> Output:
<body>
<?php IloveW3Schools.com!
$txt="W3Schools.com"; echo
"I love $txt!";
?>
</body>
</html>
Example
<html>
<body>
<?php
Output:
$txt="W3Schools.com"; echo
"I love ". $txt . "!"; IloveW3Schools.com!
?>
</body>
</html>
Example
<html>
<body>
<?php
$x=5; Output:
$y=4;
echo$x+$y; 9
?>
</body>
</html>
PHPVariablesScope
• InPHP,variablescanbedeclaredanywhereinthescript.
• Thescopeofavariableisthepartofthescriptwherethevariablecanbe
referenced/used.
PHPhasthreedifferentvariablescopes:
• local
• global
• static
GlobalandLocal Scope
Example
<html>
<body>
<?php
$x=5;//globalscope
function myTest() {
//usingxinsidethisfunctionwillgenerateanerror echo
"<p>Variable x inside function is: $x</p>";
}
myTest();
echo"<p>Variablexoutsidefunctionis:
$x</p>";?>
</body>
</html>
OUTPUT:
Variablexinsidefunctionis:
Variablexoutsidefunctionis:5
AvariabledeclaredwithinafunctionhasaLOCALSCOPEandcanonlybeaccessed within
that function:
Example
<html>
<body>
<?php
functionmyTest(){
$x=5; //localscope
echo"<p>Variablexinsidefunctionis: $x</p>";
}
myTest();
//usingxoutsidethefunctionwillgeneratean error
echo "<p>Variable x outside function is:
$x</p>";?>
</body>
</html>
OUTPUT:
Variablexinsidefunctionis:5
Variable x outside function is:
TheglobalKeyword
• Theglobalkeywordisusedtoaccessaglobalvariablefromwithinafunction.
• Todothis,usethe globalkeywordbeforethevariables(insidethefunction):
Example
<html>
<body> Output:
<?php
$x= 5; 15
$y= 10;
functionmyTest(){
global$x,$y;$y
=$x+ $y;
}
myTest();//run function
echo$y;//outputthenewvaluefor variable
$y?>
</body>
</html>
ThestaticKeyword
Todothis,usethestatickeywordwhenyoufirstdeclarethevariable:
Example
<html>
<body>
<?php
Output:
functionmyTest(){
static $x = 0;
0
echo $x;
$x++; 1
}
myTest(); 2
echo"<br>";
myTest();
echo"<br>";
myTest();
?>
</body>
</html>
echo and printStatements
• InPHPtherearetwobasicwaystogetoutput:echoandprint.
• In this tutorial we use echo (and print) in almost every example. So, this chapter
contains a little more info about those two output statements.
• echoand print are more or less the same. They are both used to output data to
the screen.
• The differencesare small: echohasno return value while printhas a return value of
1 so it can be used in expressions. echo can take multiple parameters (although
such usage is rare) while printcan take one argument. echois marginally faster
than print.
echo Statement
Theechostatementcanbeusedwithorwithoutparentheses:echoorecho().
DisplayText
Example
<html>
<body>
<?php
echo"<h2>PHPisFun!</h2>"; echo
"Hello world!<br>";
echo"I'mabouttolearn PHP!<br>";
echo"This","string","was","made","withmultiple
parameters."; ?>
</body>
</html>
OUTPUT:
PHPisFun!
Helloworld!
I'mabouttolearn PHP!
Thisstringwasmadewith multiple parameters.
DisplayVariables
Thefollowingexampleshowshowtooutputtextandvariableswiththeechostatement:
Example
<html>
<body>
<?php
$txt1="LearnPHP";$txt2
="W3Schools.com";$x= 5;
$y=4;
echo"<h2>".$txt1. "</h2>";
echo"StudyPHPat".$txt2."<br>";
echo$x+$y;
?>
</body>
</html>
OUTPUT:
LearnPHP
Study PHP at
W3Schools.com9
ThePHPprint Statement
• Theprintstatementcanbeusedwithorwithoutparentheses:printorprint().
DisplayText
Example
<html>
<body>
<?php
print"<h2>PHPisFun!</h2>";
print "Hello world!<br>";
print"I'mabouttolearn PHP!";
?>
</body>
</html>
OUTPUT:
PHPisFun!
Helloworld!
I'mabouttolearn PHP!
DisplayVariables
Thefollowingexampleshowshowtooutputtextandvariableswiththeprintstatement:
Example
<html>
<body>
<?php
$txt1="LearnPHP";
$txt2="W3Schools.com";
$x= 5;
$y=4;
print"<h2>".$txt1."</h2>";
print"StudyPHPat".$txt2."<br>"; print
$x +
$y;?>
</body>
</html>
OUTPUT:
LearnPHP
Study PHP at
W3Schools.com9
PHPObject
• Anobjectisadatatypewhichstoresdataandinformationonhowtoprocessthat data.
• InPHP,anobjectmustbeexplicitly declared.
• Firstwemustdeclareaclassofobject.Forthis, weusetheclasskeyword.A class is
a structure that can contain properties andmethods:
Example
<html>
<body>
<?php
classCar{
functionCar(){ $this-
>model ="VW";
}
}
//createanobject
$herbie=newCar();
// show object
propertiesecho
$herbie->model;?>
</body>
</html>
OUPUT:
VW
PHPNULLValue
• Nullisaspecialdatatypewhichcanhaveonlyonevalue:NULL.
• AvariableofdatatypeNULLisavariablethathasnovalueassignedtoit.
• Ifavariableiscreatedwithoutavalue,itisautomaticallyassignedavalueof NULL.
• VariablescanalsobeemptiedbysettingthevaluetoNULL:
Example
<html>
<body>
<?php
$x="Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
OUTPUT:
NULL
Constants
• Constantsarelikevariablesexceptthatoncetheyaredefinedtheycannotbe
changed or undefined.
• PHPConstants
• Aconstantisanidentifier(name)forasimplevalue.Thevaluecannotbe
changed during the script.
• Avalidconstantnamestartswithaletterorunderscore(no$signbeforethe
constant name).
Note:Unlikevariables,constantsareautomaticallyglobalacrosstheentirescript.
CreateaPHPConstant
• Tocreateaconstant,usethedefine()function.
Syntax
define(name,value,case-insensitive)
Parameters:
• name:Specifiesthenameoftheconstant
• value:Specifiesthevalueoftheconstant
• case-insensitive:Specifieswhethertheconstantnameshouldbecase-
insensitive. Default is false
Theexamplebelowcreatesaconstantwitha case-sensitivename:
Example
<html>
<body>
<?php
//case-sensitiveconstant name
define("GREETING", "Welcome to
W3Schools.com!");echoGREETING;
?>
</body>
</html>
OUTPUT:
WelcometoW3Schools.com!
Theexamplebelowcreatesaconstantwitha case-insensitivename:
Example
<html>
<body>
<?php
//case-insensitiveconstant name
define("GREETING","WelcometoW3Schools.com!",true);
echo greeting;
?>
</body>
</html>
OUPUT:
WelcometoW3Schools.com!
ConstantsareGlobal
• Constantsareautomaticallyglobalandcanbeusedacrosstheentirescript.
• Theexamplebelowusesaconstantinsideafunction,evenifitisdefinedoutside the
function:
Example
<html>
<body>
<?php
define("GREETING", "Welcome to
W3Schools.com!");functionmyTest(){
echoGREETING;
}
myTest();
?>
</body>
</html>
OUPUT:
WelcometoW3Schools.com!
PHPOperators
Operatorsareusedtoperformoperationsonvariablesand values.
PHPdividestheoperatorsinthefollowinggroups:
• Arithmeticoperators
• Assignmentoperators
• Comparisonoperators
• Increment/Decrementoperators
• Logicaloperators
• Stringoperators
• Arrayoperators
PHPArithmeticOperators
• ThePHParithmeticoperatorsareusedwith numericvaluestoperformcommon
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result
PHPAssignmentOperators
• ThePHPassignmentoperatorsareusedwithnumericvaluestowriteavalue to a
variable.
• ThebasicassignmentoperatorinPHPis"=".Itmeansthattheleftoperand gets
set to the value of the assignment expression on the right.
Assignment Sameas...Description
x=y x=y Theleftoperandgetssettothevalueofthe expression
ontheright
PHPComparisonOperators
• ThePHPcomparisonoperatorsareusedtocomparetwovalues(number or
string):
PHPIncrement/DecrementOperators
• ThePHPincrementoperatorsareusedtoincrementavariable'svalue.
• ThePHPdecrementoperatorsareusedtodecrementavariable'svalue.
Operator Name Description
PHPLogicalOperators
• ThePHPlogicaloperatorsareusedtocombineconditionalstatements.
Or Or $xor $y Trueifeither$xor$yistrue
|| Or $x||$y Trueifeither$xor$yistrue
PHPString Operators
• PHPhastwooperatorsthatarespeciallydesignedforstrings.
PHPArrayOperators
• ThePHParrayoperatorsareusedtocomparearrays.
PHPConditionalStatements
• Very often when you write code, you want to perform different actions for
differentconditions.Youcanuseconditionalstatementsinyourcodetodothis.
InPHPwehavethefollowingconditionalstatements:
• ifstatement-executessomecodeifoneconditionistrue
• if...elsestatement-executessomecodeifaconditionistrueandanothercode if that
condition is false
• if...elseif.... elsestatement-executesdifferentcodesformorethantwoconditions
• switchstatement -selectsoneofmanyblocksof codetobeexecuted
TheifStatement
• Theifstatementexecutessomecodeifoneconditionistrue.
Syntax
if(condition){
codetobeexecutedifconditionistrue;
}
Theexamplebelowwilloutput"Haveagoodday!"ifthecurrenttime(HOUR)is less
than 20:
Example
<html>
<body>
<?php
$t= date("H");
if($t<"20"){
echo"Haveagoodday!";
}
?>
</body>
</html>
OUTPUT:
Haveagoodday!
Theif...elseStatement
Syntax
if(condition){
codetobeexecutedifconditionistrue;
}else {
codetobeexecutedifconditionisfalse;
}
Example
<html>
<body>
<?php
$t= date("H");
if($t<"20"){
echo"Haveagoodday!";
}else {
echo"Haveagoodnight!";
}
?>
</body>
</html>
OUTPUT:
Haveagoodday!
Syntax
if(condition){
codetobeexecutedifthisconditionistrue;
}elseif(condition){
codetobeexecutedifthisconditionistrue;
}else {
codetobeexecutedifallconditionsarefalse;
}
The example below will output "Have a good morning!" if the currenttime is less than 10,
and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have
a good night!":
Example
<html>
<body>
<?php
$t= date("H");
echo"<p>Thehour(oftheserver)is".$t;
echo",andwillgivethefollowingmessage:</p>"; if
($t <"10") {
echo"Haveagoodmorning!";
}elseif($t<"20"){
echo"Haveagoodday!";
}else {
echo"Haveagoodnight!";
}
?>
</body>
</html>
OUTPUT:
Thehour(oftheserver)is01,andwillgivethefollowingmessage: Have a
good morning!
TheswitchStatement
• Theswitchstatementisusedtoperformdifferentactionsbasedon
different conditions.
Usetheswitchstatementtoselectoneofmanyblocksofcodetobeexecuted.
Syntax
switch (n) {
caselabel1:
codetobeexecutedifn=label1;
break;
caselabel2:
codetobeexecutedifn=label2;
break;
caselabel3:
codetobeexecutedifn=label3;
break;
...
default:
codetobeexecutedifnisdifferentfromall labels;
}
<html>
<body>
<?php
$favcolor = "red";
switch($favcolor){
case"red":
echo"Yourfavoritecolorisred!";
break;
case"blue":
echo"Yourfavoritecolorisblue!"; break;
case"green":
echo"Yourfavoritecolorisgreen!"; break;
default:
echo"Yourfavoritecolorisneitherred,blue,nor green!";
}
?>
</body>
</html>
OUTPUT:
Yourfavoritecolorisred!
PHPLoops
Oftenwhenyouwritecode,youwantthesameblockofcodetorunoverandoveragain in arow.
Insteadofaddingseveralalmostequalcode-linesinascript, we canuse loops to perform a
task like this.
InPHP,wehavethefollowinglooping statements:
• while-loopsthroughablockofcodeaslongasthespecifiedconditionistrue
• do...while-loopsthroughablockofcodeonce,andthenrepeatstheloopas long as
the specified condition is true
• for-loopsthroughablockof codeaspecifiednumberoftimes
• foreach-loopsthrougha blockof codeforeachelementinanarray
ThePHPwhileLoop
Syntax
while(conditionistrue){
codetobe executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1
each time the loop runs ($x++):
Example
<html>
<body>
<?php
$x= 1;
while($x<=5){
echo"Thenumberis:$x
<br>"; $x++;
}
?>
</body>
</html>
OUTPUT:
Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5
ThePHPdo...whileLoop
Thedo...whileloopwillalwaysexecutetheblockofcodeonce,itwillthencheckthe condition,
and repeat the loop while the specified condition is true.
Syntax
do {
codetobeexecuted;} while
(condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop willwrite
some output, and then increment the variable $x with 1. Then the condition is checked
(is $x less than, or equal to 5?), and the loop will continue to run as longas $x is less
than, or equal to 5:
Example
<html>
<body>
<?php
$x=1;
do {
echo"Thenumberis:$x<br>";
$x++;
}while($x<=
5); ?>
</body>
</html>
OUTPUT:
Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5
Notice that in a do whileloop the condition is tested AFTER executing the statements
within the loop. This means that the do whileloop would execute its statements at least
once, even if the condition is false the first time.
Example
<html>
<body>
<?php
$x= 6;
do{
echo"Thenumberis:$x<br>";
$x++;
}while($x<=
5); ?>
</body>
</html>
OUTPUT:
Thenumberis:6
forLoops
• PHPforloopsexecuteablockof codeaspecifiednumberoftimes.
ThePHPforLoop
• Theforloopisusedwhenyouknowinadvancehowmanytimesthescript should
run.
Syntax
for(initcounter;testcounter;incrementcounter){
codetobe executed;
}
Parameters:
• initcounter:Initializetheloopcountervalue
• testcounter:Evaluatedforeachloopiteration.IfitevaluatestoTRUE,the loop
continues. If it evaluates to FALSE, the loop ends.
• incrementcounter:Increasestheloopcountervalue
Example
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo"Thenumberis:$x<br>";
}
?>
</body>
</html>
OUTPUT:
ThePHPforeachLoop
• Theforeachloopworksonlyonarrays,andisused toloopthrougheach
key/value pair in an array.
Syntax
foreach($arrayas$value)
{
codetobe executed;
}
• Foreveryloopiteration,thevalueofthecurrentarrayelementisassignedto
$valueandthearraypointerismovedbyone,untilitreachesthelastarray element.
<html>
<body>
<?php
$colors=array("red","green","blue","yellow");
foreach($colorsas $value)
{echo"$value<br>";
}
?>
</body>
</html>
OUTPUT:
red
green
blue
yellow
WorkingwithArrays
• Therearetwowaystocreateindexedarrays:
• Theindexcanbeassignedautomatically(indexalwaysstartsat0),likethis:
• $cars=array("Volvo","BMW","Toyota");
• ortheindexcanbeassignedmanually:
• $cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
• Thefollowingexamplecreatesanindexedarraynamed$cars,assigns
three elements to it, and then prints a text containing the arrayvalues:
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0]. ",".$cars[1] ." and".$cars[2].".";
?>
</body>
</html>
OUTPUT:
IlikeVolvo,BMWandToyota.
GetTheLengthofanArray-Thecount()Function
Thecount()functionisusedtoreturnthelength(thenumberofelements)ofanarray:
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota"); echo
count($cars);
?>
</body>
</html>
OUTPUT:
3
LoopThroughanIndexedArray
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++){ echo
$cars[$x];
echo"<br>";
}
?>
</body>
</html>
OUTPUT:
Volvo
BMW
Toyota
PHPAssociativeArrays
• Associativearraysarearraysthatusenamedkeysthatyouassigntothem.
• Therearetwowaystocreateanassociativearray:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
• Thenamedkeyscanthenbeusedinascript:
Example
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo
"Peter is ". $age['Peter'] . " years old.";
?>
</body>
</html>
OUTPUT:
Peteris35yearsold.
LoopThroughanAssociative Array
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x => $x_value) {
echo"Key=".$x.",Value=".$x_value; echo
"<br>";
}
?>
SortingArrays
Theelementsinanarraycanbesortedinalphabeticalornumericalorder, descending
or ascending.
• sort()-sortarraysinascendingorder
• rsort()-sortarraysindescending order
• asort()-sortassociativearraysinascendingorder,accordingtothevalue
• ksort()-sortassociativearraysinascendingorder,accordingtothekey
• arsort()-sortassociativearraysindescending order,accordingtothevalue
• krsort()-sortassociativearraysindescendingorder,accordingtothekey
SortArrayinAscendingOrder-sort()
Thefollowingexamplesortstheelementsofthe$carsarrayinascending alphabetical
order:
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++){
echo $cars[$x];
echo"<br>";
}
?>
</body>
</html>
OUTPUT:
BMW
Toyota
Volvo
Example
<?php
$numbers=array(4,6,2,22,
11);sort($numbers);
?>
OUTPUT:
2
4
6
11
22
SortArray(AscendingOrder),AccordingtoValue -asort()
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
OUTPUT:
Key=Peter,Value=35
Key=Ben, Value=37
Key=Joe, Value=43
SortArray(AscendingOrder),AccordingtoKey-ksort()
Thefollowingexamplesortsanassociativearrayinascendingorder,accordingtothe key:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
OUTPUT:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter,Value=35
SortArray(DescendingOrder),AccordingtoValue-arsort()
Thefollowingexamplesortsanassociativearrayindescendingorder,accordingtothe value:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
OUTPUT:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter,Value=35
SortArray(DescendingOrder),AccordingtoKey-krsort()
Thefollowingexamplesortsanassociativearrayindescendingorder,accordingtothe key:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
OUTPUT:
Key=Peter,Value=35
Key=Joe, Value=43
Key=Ben, Value=37
• Anarraystoresmultiplevaluesinonesinglevariable.
• Inthefollowingexample$carsisanarray.ThePHPvar_dump()functionreturns the
data type and value:
Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
OUTPUT:
array(3){[0]=>string(5)"Volvo"[1]=>string(3)"BMW"[2]=>string(6)"Toyota"}
Functions
• TherealpowerofPHPcomesfromitsfunctions;ithasmorethan1000built-in
functions.
PHPUserDefinedFunctions
• Besidesthebuilt-inPHPfunctions,wecancreateourownfunctions.
• Afunctionisablockofstatementsthatcanbeusedrepeatedlyinaprogram.
• Afunctionwillnotexecuteimmediatelywhenapageloads.
• Afunctionwillbeexecutedbya calltothefunction.
CreateaUserDefinedFunctionin PHP
Auser-definedfunctiondeclarationstartswiththewordfunction:
Syntax
functionfunctionName(){
codetobe executed;
}
• FunctionnamesareNOTcase-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace ( } )
indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:
Example
<html>
<body>
<?php
function writeMsg()
echo"Helloworld!";
}
writeMsg();
?>
</body>
</html>
OUTPUT:
Helloworld!
PHPFunction Arguments
Example
<html>
<body>
<?php
function familyName($fname) {
echo"$fnameRefsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("KaiJim");
familyName("Borge");
?>
</body>
</html>
OUTPUT:
JaniRefsnes.
HegeRefsnes.
StaleRefsnes.
Kai JimRefsnes.
BorgeRefsnes.
Thefollowingexamplehasafunctionwithtwo arguments($fnameand$year):
Example
<html>
<body>
<?php
functionfamilyName($fname,$year){
echo"$fnameRefsnes.Bornin$year<br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai
Jim","1983"); ?>
</body>
</html>
OUTPUT:
• The following example shows how to use a default parameter. If we call the
functionsetHeight()withoutargumentsittakesthedefaultvalueasargument:
Example
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo"Theheightis:$minheight<br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
OUTPUT:
Theheightis:350
The height is : 50
Theheightis:135
The height is : 80
PHPFunctions-Returningvalues
• Toletafunctionreturnavalue,usethereturnstatement:
Example
<html>
<body>
<?php
functionsum($x,$y){
$z=$x+$y; return
$z;
}
echo"5+10=".sum(5,10)."<br>";
echo"7+13=".sum(7,13)."<br>"; echo
"2 + 4 = ". sum(2,4);
?>
</body>
</html>OU
TPUT:5+1
0=15
7+13=20
2+4 =6
WorkingwithFiles
•Filehandlingisanimportantpartofanywebapplication.Youoftenneedtoopen and
process a file for different tasks.
PHPManipulatingFiles
PHPhasseveralfunctionsforcreating,reading,uploading,andeditingfiles.
Becarefulwhenmanipulatingfiles!
• Whenyouaremanipulatingfilesyoumustbeverycareful.
• You can do a lot of damage if you do something wrong. Common errors are:
editing the wrong file, filling a hard-drive with garbage data, and deleting the
content of a file by accident.
PHPreadfile()Function
• Thereadfile()functionreadsafileandwritesittotheoutputbuffer.
• Assumewehaveatextfilecalled"webdictionary.txt",storedontheserver,that looks
like this:
AJAX=AsynchronousJavaScriptandXML
CSS = Cascading Style Sheets
HTML=HyperTextMarkupLanguage
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML=EXtensibleMarkupLanguage
• ThePHPcodetoreadthefileandwriteittotheoutputbufferisasfollows(the readfile()
function returns the number of bytes read on success):
Example
<html>
<body>
<?php
echo readfile("webdictionary.txt");
?>
</body>
</html>
OUTPUT:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured
Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup
Language236
• Thereadfile()functionisusefulif allyouwanttodoisopenupafileandreadits contents.
File Open/Read/Close
PHPOpenFile-fopen()
The first parameter of fopen() contains the name of the file to be opened and thesecond
parameter specifies in which mode the file should be opened. The following example
also generates a message if the fopen() function is unable to open the specified file:
Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!"); echo
fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
OUTPUT:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured
QueryLanguageSVG=ScalableVectorGraphicsXML=EXtensibleMarkupLanguage
Thefilemaybeopenedinoneofthefollowing modes:
Modes Description
r Openafileforreadonly.Filepointerstartsatthebeginningofthefile
x Createsanewfileforwriteonly.ReturnsFALSEandanerroriffilealreadyexists
r+ Openafileforread/write.Filepointerstartsatthebeginningofthefile
w+ Openafileforread/write.Erasesthecontentsofthefileorcreatesanewfileifit
doesn'texist.Filepointerstartsatthebeginningofthe file
a+ Openafileforread/write.Theexistingdatainfileispreserved.Filepointerstarts
attheendof thefile.Createsanewfileif thefiledoesn'texist
x+ Createsanewfileforread/write.ReturnsFALSEandanerroriffile already
Exists
PHPReadFile -fread()
• Thefread()functionreadsfromanopen file.
• Thefirstparameterof fread()containsthenameofthefiletoreadfromandthe second
parameter specifies the maximum number of bytes to read.
• ThefollowingPHPcodereadsthe"webdictionary.txt"filetotheend:
fread($myfile,filesize("webdictionary.txt"));
PHPCloseFile-fclose()
• Thefclose()functionisusedtocloseanopenfile.
• It'sagoodprogrammingpracticetocloseallfilesafteryouhavefinishedwith them.
You don't want an open file running around on your server taking up
resources!
• Thefclose()requiresthenameofthefile(oravariablethatholdsthefilename) we
want to close:
<?php
$myfile=fopen("webdictionary.txt",
"r");//somecodetobeexecuted....
fclose($myfile);
?>
PHPReadSingleLine -fgets()
• Thefgets()functionisusedtoreadasinglelinefromafile.
• Theexamplebelowoutputsthefirstlineofthe"webdictionary.txt"file:
Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!"); echo
fgets($myfile);
fclose($myfile);
?>
OUTPUT:
AJAX=AsynchronousJavaScriptandXML
Afteracalltothefgets()function,thefilepointerhasmovedtothenextline.
PHPCheckEnd-Of-File-feof()
• Thefeof()functionchecksifthe"end-of-file" (EOF)hasbeenreached.
• Thefeof()functionisusefulforloopingthroughdataof unknownlength.
• Theexamplebelowreadsthe"webdictionary.txt"filelinebyline,until end-of-file is
reached:
Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!");
//Outputonelineuntilend-of-file
while(!feof($myfile)) {
echofgets($myfile). "<br>";
}
fclose($myfile);
?>
OUTPUT:
AJAX=AsynchronousJavaScriptandXML
CSS = Cascading Style Sheets
HTML=HyperTextMarkupLanguage
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML=EXtensibleMarkupLanguage
PHPReadSingleCharacter -fgetc()
• Thefgetc()functionisusedtoreadasinglecharacterfromafile.
• Theexamplebelowreadsthe"webdictionary.txt"filecharacterbycharacter,until end-
of-file is reached:
Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!");
//Outputonecharacteruntilend-of-file
while(!feof($myfile)){
echofgetc($myfile);
}
fclose($myfile);
?>
OUTPUT:
AJAX=AsynchronousJavaScriptandXMLCSS=CascadingStyleSheetsHTML=Hyper Text
Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query
Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language
• Afteracalltothefgetc()function,thefilepointermovestothenextcharacter.
File Create/Write
PHPCreateFile -fopen()
• Thefopen()functionisalsousedtocreateafile.Maybealittleconfusing,butin PHP, a
file is created using the same function used to openfiles.
• Ifyouusefopen()onafilethatdoesnotexist,itwillcreateit,giventhatthefileis opened for
writing (w) or appending (a).
• Theexamplebelowcreatesanewfilecalled"testfile.txt".Thefilewillbecreated in the
same directory where the PHP code resides:
Example
$myfile=fopen("testfile.txt","w")
PHPFilePermissions
Ifyouarehavingerrorswhentryingtogetthiscodetorun,checkthatyouhave granted
your PHP file access to write information to the hard drive.
PHPWritetoFile- fwrite()
• Thefwrite()functionisusedtowritetoafile.
• Thefirstparameteroffwrite()containsthenameofthefiletowritetoandthe second
parameter is the string to be written.
• Theexamplebelowwritesacoupleofnamesintoanewfilecalled"newfile.txt":
Example
<?php
$myfile=fopen("newfile.txt","w")ordie("Unabletoopen file!");
$txt = "John Doe\n";
fwrite($myfile,$txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that wewrote to the file "newfile.txt" twice. Each timewewrote to the file wesent
the string $txt that first contained "John Doe" and second contained "Jane Doe". After
we finished writing, we closed the file using the fclose() function.
Ifweopenthe"newfile.txt"fileitwouldlooklike this:
JohnDoe
JaneDoe
PHPOverwriting
• Now that "newfile.txt" contains some data we can show what happens when we
open an existingfilefor writing. All the existingdata willbe ERASEDand westart
with an empty file.
• In the example below we open our existing file "newfile.txt", and write some new
data into it:
Example
<?php
$myfile=fopen("newfile.txt","w")ordie("Unabletoopen file!");
$txt = "Mickey Mouse\n";
fwrite($myfile,$txt);
$txt="MinnieMouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
OUTPUT:
MickeyMouse
MinnieMouse
PHPftp_fput()Function
Example
• Openlocalfile,anduploadittoafileontheFTPserver:
<?php
//connectandlogintoFTPserver
$ftp_server="ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to
$ftp_server");$login=ftp_login($ftp_conn,$ftp_username,$ftp_userpass);
//openfilefor reading
$file="test.txt";
$fp=fopen($file,"r");
//uploadfile
if(ftp_fput($ftp_conn,"somefile.txt",$fp,FTP_ASCII))
{
echo"Successfullyuploaded$file.";
}
else
{
echo"Erroruploading$file.";
}
//closethisconnectionandfilehandler
ftp_close($ftp_conn);
fclose($fp);
?>
DefinitionandUsage
• Theftp_fput()functionuploadsfromanopenfileandsavesittoafileonthe FTP
server.
Syntax
ftp_fput(ftp_connection,remote_file,open_file,mode,startpos);
Parameter Description
ftp_connectionRequired.SpecifiestheFTPconnectionto use
remote_file Required.Specifiesthefilepathtouploadto
open_file Required.Specifiesanopenlocalfile.Readingstopsatend
offile
mode Required.Specifiesthetransfermode.Possiblevalues:
FTP_ASCIIorFTP_BINARY
startpos Optional.Specifiesthepositionintheremotefiletostart
uploadingto
WorkingwithDatabases PHP
MySQL Database
• WithPHP,youcanconnecttoandmanipulatedatabases.
• MySQListhemostpopulardatabasesystemusedwithPHP.
Whatis MySQL?
• MySQLisadatabasesystemusedontheweb
• MySQLisadatabasesystemthatrunsonaserver
• MySQLisidealforbothsmallandlargeapplications
• MySQL isveryfast,reliable,andeasytouse
• MySQLusesstandardSQL
• MySQL compilesonanumberofplatforms
• MySQLisfreetodownloadanduse
• MySQLisdeveloped,distributed,andsupportedbyOracleCorporation
Databasesareusefulforstoringinformationcategorically.Acompanymayhavea database
with the following tables:
• Employees
• Products
• Customers
• Orders
PHP+MySQLDatabaseSystem
• PHPcombinedwithMySQLarecross-platform(youcandevelopinWindowsand serve
on a Unix platform)
PHPConnecttoMySQL
PHP5andlatercanworkwithaMySQLdatabaseusing:
• MySQLiextension (the"i"standsforimproved)
• PDO(PHPDataObjects)
EarlierversionsofPHPusedtheMySQLextension.However,thisextension was
deprecated in 2012.
ShouldIUseMySQLi orPDO?
Ifyouneedashortanswer,itwouldbe"Whateveryoulike". Both
• PDOwillworkon12differentdatabasesystems,whereasMySQLiwillonlywork with
MySQL databases.
• So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queriesincluded.
• Bothareobject-oriented,butMySQLialsooffersaproceduralAPI.
• BothsupportPreparedStatements.PreparedStatementsprotectfromSQL
injection, and are very important for web application security.
MySQLExamplesinBothMySQLiandPDOSyntax
Inthis,andinthefollowingchapterswedemonstratethreewaysofworkingwith PHP
and MySQL:
• MySQLi(object-oriented)
• MySQLi(procedural)
• PDO
MySQLiInstallation
• ForLinuxandWindows:TheMySQLiextensionisautomaticallyinstalledin most
cases, when php5 mysql package is installed.
• Forinstallationdetails,goto:http://php.net/manual/en/mysqli.installation.php
• PDO Installation
• Forinstallationdetails,goto:http://php.net/manual/en/pdo.installation.php
OpenaConnectiontoMySQL
• BeforewecanaccessdataintheMySQLdatabase, weneedtobeable to
connect to the server:
Example(MySQLiObject-Oriented)
<?php
$servername="localhost";
$username="username";
$password="password";
//Create connection
$conn=newmysqli($servername,$username,$password);
//Check connection
if($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}
echo"Connected
successfully"; ?>
Example(MySQLiProcedural)
<?php
$servername="localhost";
$username="username";
$password="password";
//Create connection
$conn=mysqli_connect($servername,$username,$password);
//Checkconnection if
(!$conn) {
die("Connectionfailed:".mysqli_connect_error());
}
echo"Connected
successfully"; ?>
Example (PDO)
<?php
$servername="localhost";
$username="username";
$password="password";
try{
$conn=newPDO("mysql:host=$servername;dbname=myDB",
$username,$password);
//setthePDOerrormodetoexception$conn-
>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);echo
"Connectedsuccessfully";
}
catch(PDOException$e)
{
echo"Connectionfailed:".$e->getMessage();
}
?>
NoticethatinthePDOexampleabovewehavealsospecifiedadatabase(myDB).PDO require
a valid database to connect to. If no database is specified, an exception is thrown.
ClosetheConnection
Theconnectionwillbeclosedautomaticallywhenthescriptends.Toclosethe connection
before, use the following:
Example(MySQLiObject-Oriented)
$conn->close();
Example(MySQLiProcedural)
mysqli_close($conn);
Example (PDO)
$conn= null;
PHPCreateaMySQLDatabase
• Adatabaseconsistsofoneormore tables.
• YouwillneedspecialCREATEprivilegestocreateortodeleteaMySQL
database.
• CreateaMySQLDatabaseUsingMySQLi
• TheCREATEDATABASEstatementisusedtocreateadatabaseinMySQL.
• Thefollowingexamplescreateadatabasenamed"myDB":
Example(MySQLiObject-oriented)
<?php
$servername="localhost";
$username="username";
$password="password";
//Create connection
$conn=newmysqli($servername,$username,
$password);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}
//Create database
$sql="CREATEDATABASEmyDB";
if($conn->query($sql)===TRUE){
echo"Databasecreated
successfully"; } else {
echo"Errorcreatingdatabase:".$conn->error;
}
$conn-
>close();?>
PHPCreateMySQLTable
• Adatabasetablehasitsownuniquenameandconsistsofcolumnsandrows.
• CreateaMySQL TableUsingMySQLi
• TheCREATETABLEstatementisusedtocreateatableinMySQL.
• We willcreateatablenamed"MyGuests",withfivecolumns:"id","firstname",
"lastname", "email" and "reg_date":
CREATETABLEMyGuests(
idINT(6)UNSIGNEDAUTO_INCREMENTPRIMARY
KEY, firstname VARCHAR(30) NOT NULL,
lastnameVARCHAR(30)NOT
NULL, email VARCHAR(50),
reg_dateTIMESTAMP
)
Notesonthetableabove:
• Thedatatypespecifieswhattypeofdata thecolumncanhold.Foracomplete
reference of all the available data types, go to our Data Typesreference.
Afterthedatatype,youcanspecifyotheroptionalattributesforeach column:
Eachtableshouldhaveaprimarykeycolumn(inthiscase:the"id"column).Its value
must be unique for each record in the table.
ThefollowingexamplesshowshowtocreatethetableinPHP:
Example(MySQLiObject-oriented)
<?php
$servername="localhost";
$username="username";
$password="password";
$dbname="myDB";
//Create connection
$conn=newmysqli($servername,$username,$password,
$dbname);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}
//sqltocreatetable
$sql="CREATETABLEMyGuests(
idINT(6)UNSIGNEDAUTO_INCREMENTPRIMARY
KEY, firstname VARCHAR(30) NOT NULL,
lastnameVARCHAR(30)NOT
NULL, email VARCHAR(50),
reg_dateTIMESTAMP
)";
if($conn->query($sql)===TRUE){ echo
"Table MyGuests created
successfully";}else{
echo"Errorcreatingtable:".$conn->error;
}
$conn-
>close();?>
PHPInsertDataIntoMySQL
InsertDataIntoMySQLUsing MySQLi
Herearesomesyntaxrulestofollow:
• TheSQLquerymustbequotedinPHP
• StringvaluesinsidetheSQLquerymustbequoted
• Numericvaluesmustnotbequoted
• ThewordNULLmustnotbequoted
TheINSERTINTOstatementisusedtoaddnewrecordstoaMySQLtable:
INSERTINTOtable_name(column1,column2,column3,...)
VALUES (value1, value2, value3,...)
Note:IfacolumnisAUTO_INCREMENT(likethe"id"column)orTIMESTAMP(likethe
"reg_date" column), it is no need to be specified in the SQL query; MySQL will
automatically add the value.
Thefollowingexamplesaddanewrecordtothe"MyGuests"table:
Example(MySQLiObject-oriented)
<?php
$servername="localhost";
$username="username";
$password="password";
$dbname="myDB";
//Createconnection
$conn=newmysqli($servername,$username,$password,
$dbname);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}
$sql="INSERTINTOMyGuests(firstname,lastname,email) VALUES
('John', 'Doe', 'john@example.com')";
if($conn->query($sql)===TRUE){ echo
"New record created
successfully";}else{
echo"Error:".$sql."<br>".$conn->error;
}
$conn-
>close();?>
Example:
StudentApplicationusingPHPandMysql
aa.html:
<!DOCTYPE HTML>
<html>
<head>
<title>Student
Table</title></head>
<body>
Mark2<br><inputtype="text"name="m2"><br><input
type="submit" value="ok">
</form>
</div>
</body>
</html>
Conn.php:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="sample";
//Create connection
$conn=newmysqli($servername,$username,$password,$dbname);
//Check connection
if($conn->connect_error)
die("Connectionfailed:".$conn->connect_error);
echo "Connected
successfully";//connecttable
$sql="descstudent";if($conn-
>query($sql)==TRUE)
echo"<br>";
echo"connectedtothetable";
else
echo"error";
//Inserting the
contentsecho"<br>";
//insertionfromhtml
$sname=$_POST['sname'];
$regno=$_POST['regno'];
$m1=$_POST['m1'];
$m2=$_POST['m2'];
$sql11="insertintostudentvalues('$sname',$regno,$m1,$m2)";
if($conn->query($sql11)==TRUE)
{
echo"inserted";
else
{echo"error";}
echo "<br>";
$sql1="select*fromstudent";
$result=$conn->query($sql1); if
($result->num_rows > 0) {
//outputdataofeachrow
echo"<b>SnameRegnoM1M2</b><br>";
while($row = $result->fetch_assoc()) {
echo$row["sname"]."".$row["regno"]."".$row["m1"]."".$row
["m2"]."<br>";
}else {
echo"emptytable";
$conn-
>close();?>
OUTPUT:
UNIT-5
PERL
Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming
language. It was developed by Larry Wall, in 1987. There is no official Full form
of the Perl, but still, the most used expansion is “Practical Extraction and
Reporting Language“.
Why Perl?
Perl has many reasons for being popular and in demand. Few of the reasons
are mentioned below:
Easy to start: Perl is a high-level language so it is closer to other popular
programming languages like C, C++ and thus, becomes easy to learn for
anyone.
Text-Processing: As the acronym “Practical Extraction and Reporting
Language” suggest that Perl has the high text manipulation abilities by which
it can generate reports from different text files easily. Also, it can convert the
files into some another form.
Contained best Features: Perl contains the features of different languages
like C, sed, awk, and sh etc. which makes the Perl more useful and
productive.
System Administration: Due to having the different scripting languages
capabilities Perl make the task of system administration very easy. Instead
of becoming dependent on many languages, just use Perl to complete out
the whole task of system administration. In Spite of this Perl also used in
web programming, web automation, GUI programming etc.
Web and Perl: Perl can be embedded into web servers to increase its
processing power and it has the DBI package, which makes web-database
integration very easy.
Beginning with Perl Programming:
Finding a Interpreter: There are various online IDEs which can be used to
run Perl programs without installing.
Windows: There are various IDEs to run Perl programs or
scripts: Padre, Eclipse with EPIC plugin etc.
Example: A simple program to print Welcome to GFG!
# Perl program to print Welcome to GFG!
#!/usr/bin/perl
Fundamentals of Perl
Variables
Variables are user-defined words that are used to hold the values passed to the
program which will be used to evaluate the Code. Every Perl program contains
values on which the Code performs its operations. These values can’t be
manipulated or stored without the use of a Variable. A value can be processed
only if it is stored in a variable, by using the variable’s name.
A value is the data passed to the program to perform manipulation operations.
This data can be either numbers, strings, characters, lists, etc.
Example:
Values:
5
geeks
15
Variables:
$a = 5;
$b = "geeks";
$c = 15;
Operators
Operators are the main building block of any programming language. Operators
allow the programmer to perform different kinds of operations on operands.
These operators can be categorized based upon their different functionality:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary Operator
# Operands
$a = 10;
$b = 4;
$c = true;
$d = false;
if ($a == $b)
else
Output:
Addition is: 14
Subtraction is: 6
Equal To Operator is False
AND Operator: 4
Bitwise AND: 0
Addition Assignment Operator: 14
Number and its Types
A Number in Perl is a mathematical object used to count, measure, and perform
various mathematical operations. A notational symbol that represents a number
is termed a numeral. These numerals, in addition to their use in mathematical
operations, are also used for ordering(in the form of serial numbers).
Types of numbers:
Integers
Floating Numbers
Hexadecimal Numbers
Octal Numbers
Binary Numbers
#!/usr/bin/perl
# Integer
$a = 20;
# Floating Number
$b = 20.5647;
# Scientific value
$c = 123.5e-10;
# Hexadecimal Number
$d = 0xc;
# Octal Number
$e = 074;
# Binary Number
$f = 0b1010;
Output:
Integer: 20
Float Number: 20.5647
Scientific Number: 1.235e-08
Hex Number: 12
Octal number: 60
Binary Number: 10
DataTypes
Data types specify the type of data that a valid Perl variable can hold. Perl is a
loosely typed language. There is no need to specify a type for the data while
using it in the Perl program. The Perl interpreter will choose the type based on
the context of the data itself.
Scalars
It is a single unit of data which can be an integer number, floating-point, a
character, a string, a paragraph, or an entire web page.
Example:
# Perl program to demonstrate
# scalars variables
# a string scalar
$name = "Alex";
# Integer Scalar
$rollno = 13;
$percentage = 87.65;
# In hexadecimal form
$hexadec = 0xcd;
# Alphanumeric String
$alphanumeric = "gfg21";
# special character in string scalar
$specialstring = "^gfg";
Output:
Name = Alex
Roll number = 13
Percentage = 87.65
Hexadecimal Form = 205
String with alphanumeric values = gfg21
String with special characters = ^gfg
Arrays
An array is a variable that stores the value of the same data type in the form of
a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name.
@number = (40, 55, 63, 17, 22, 68, 89, 97, 89)
It will create an array of integers that contains the values 40, 55, 63, 17, and
many more. To access a single element of an array, we use the ‘$’ sign.
$number[0]
It will produce the output as 40.
Array creation and accessing elements:
#!/usr/bin/perl
# Define an array
# using qw function
print "$arr1[0]\n";
print "$arr1[3]\n";
print "$arr2[-1]\n";
print "$arr2[-3]\n";
Output:
@list = (1..10);
# Non-interpolated string
# Interpolated string
print("$strng1\n$strng2");
Output:
$email = "GeeksforGeeks0402@gmail.com";
print("$email\n");
# interpolation of '@'
$email = "GeeksforGeeks0402\@gmail.com";
print($email);
Output:
GeeksforGeeks0402.com
GeeksforGeeks0402@gmail.com
Escaping the escape character:
The backslash is the escape character and is used to make use of escape
sequences. When there is a need to insert the escape character in an
interpolated string, the same backslash is used, to escape the substitution of
escape character with ” (blank). This allows the use of escape characters in the
interpolated string.
#!/usr/bin/perl
print($string1);
Output:
Hashes(Associative Arrays)
It is a set of key-value pairs. It is also termed as the Associative Arrays. To
declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we
use the ‘$’ symbol which is followed by the key in braces.
Creating and Accessing Hash elements:
#!/usr/bin/perl
# Initializing Hash by
$Fruit{'Mango'} = 10;
$Fruit{'Apple'} = 20;
$Fruit{'Strawberry'} = 30;
# printing elements of Hash
print "$Fruit{'Mango'}\n";
print "$Fruit{'Apple'}\n";
print "$Fruit{'Strawberry'}\n";
%Fruit2 = ('Mango' => 45, 'Apple' => 42, 'Strawberry' => 35);
print "$Fruit2{'Mango'}\n";
print "$Fruit2{'Apple'}\n";
print "$Fruit2{'Strawberry'}\n";
Output:
#!/usr/bin/perl
# Decision-Making statements
$a = 10;
$b = 15;
# if condition to check
# for even number
if($a % 2 == 0 )
if($b % 2 == 0 )
else
Output:
Even Number
Odd Number
Loops
Looping in programming languages is a feature that facilitates the execution of
a set of instructions or functions repeatedly while some condition evaluates to
true. Loops make the programmer’s task simpler. Perl provides the different
types of loop to handle the condition based situation in the program. The loops
in Perl are :
for loop
#!/usr/bin/perl
# for loop
print("For Loop:\n");
print "GeeksForGeeks\n"
Output:
For Loop:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
foreach loop
#!/usr/bin/perl
# Perl program to illustrate
# Array
# foreach loop
print("For-each Loop:\n");
Output:
For-each Loop:
GEEKS 4 GEEKS
while and do…. while loop
#!/usr/bin/perl
# while loop
$count = 3;
print("While Loop:\n");
$count = $count - 1;
print "GeeksForGeeks\n";
print("\ndo...while Loop:\n");
$a = 10;
# do..While loop
do {
Output:
While Loop:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
do...while Loop:
10 9 8 7 6 5 4 3 2 1
Subroutines
What are Subroutines?
A Perl function or subroutine is a group of statements that together perform a
specific task. In every programming language user want to reuse the code. So
the user puts the section of code in function or subroutine so that there will be
no need to write code again and again.
Example:
#!/usr/bin/perl
# defining subroutine
sub ask_user
# calling subroutine
# &ask_user();
ask_user();
Output:
Hello Geeks!
Multiple Subroutines
Multiple subroutines in Perl can be created by using the keyword ‘multi’. This
helps in the creation of multiple subroutines with the same name.
Example:
multi Func1($var){statement};
multi Func1($var1, $var2){statement1; statement2;}
Example:
#!/usr/bin/perl
multi Factorial(0)
1; # returning 1
# Recursive Function
# to calculate Factorial
print Factorial(15);
Output:
3628800
To know more about Multiple Subroutines, please refer to Multiple Subroutines
in Perl
Modules and Packages
A module in Perl is a collection of related subroutines and variables that
perform a set of programming tasks. Perl Modules are reusable. Perl module is
a package defined in a file having the same name as that of the package and
having extension .pm. A Perl package is a collection of code which resides in its
own namespace.
To import a module, we use require or use functions. To access a function or a
variable from a module, :: is used.
Examples:
#!/usr/bin/perl
use Calculator;
$a = 5;
$b = 10;
# Subroutine call
Calculator::multiplication($a, $b);
print "\nEnter two numbers to divide";
$a = 45;
$b = 5;
# Subroutine call
Calculator::division($a, $b);
File Handling
In Perl, a FileHandle associates a name to an external file, that can be used
until the end of the program or until the FileHandle is closed. In short, a
FileHandle is like a connection that can be used to modify the contents of an
external file and a name is given to the connection (the FileHandle) for faster
access and ease.
The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which
represent Standard Input, Standard Output, and Standard Error devices
respectively.
Reading from and Writing to a File using FileHandle
Reading from a FileHandle can be done through the print function.
$firstline = <fh>;
print "$firstline\n";
Output :
#!/usr/bin/perl
# Using predefined modules
use warnings;
use strict;
my $filename = 'C:\Users\GeeksForGeeks\GFG.txt';
if(-e $filename)
# If File exists
else
{
# If File doesn't exists
#!/usr/bin/perl
use Excel::Writer::XLSX;
my $Excelsheet = $Excelbook->add_worksheet();
$Excelbook->close;
Output:
use 5.016;
Output:
A2: GeeksForGeeks