PHP notes - chapter 1st
PHP notes - chapter 1st
PHP notes - chapter 1st
WhatisPHP?
PHPis ageneral-purpose scriptinglanguage especiallysuited to web development.
● PHP standsforPHPhypertext preprocessor
● PHPis aserver sideprogramminglanguagethat isembeddedinHTML.
● PHPallowswebdeveloperstocreatedynamiccontentsthatinteractwithdatabase,session
management etc.
● ItisintegratedwithpopulardatabaseslikeMySQL,postgreSQL,Oracleetc.
● PHPis basicallyused for developing webapps
● PHPis opensource
WhyPHP?
● PHPrunsondifferentOSplatforms like
o Windows(WAMP)
o Linux(LAMP)
o MAC OS (MAMP)
● PHPis aninterpretedlanguage.
● PHPiscompatiblewithalmostallserversbutthemostusedserveris apache.
● PHPisopensourceso itisfreeto downloadand use
● PHPis easytouseandwidely used.
CharacteristicsofPHP
● Simplicity
● Efficiency
● Security
● Flexibility
● Familiarity
Page|1
AdvantagesofPHP:
● Most important advantage of PHPisthatit’sopensourceandfreefromcost.Itcanbe
downloaded anywhere and readily available to use for web applications.
● It is platform independent. PHP based applications can run on any OS like UNIX,
Linux and Windows, etc.
● Application can easilybe loadedwhich arebased onPHPandconnectedtodatabase. It’s
mainly used due to its faster rate ofloadingoverslowinternetspeedthananother
programming language.
● It has less learning curve, because it is simple and straightforward to use. Someone
familiar with C programming can easily work on PHP.
● It is more stable from a few years with assistance of providing continuoussupportto
various versions.
● It helps in reusing an equivalent code and no got to write lengthy code and
sophisticated structure for event of web applications.
● Ithelpsinmanagingcode easily.
● Ithas powerful librarysupporttousevariousfunction modules fordatarepresentation.
SyntaxofPHP:
APHPscriptcanbeplacedanywhereinthedocument.A
PHP script starts with <?php and ends with ?>
<?php
//PHPcodegoes here
?>
<?php
echo"Hello, World!";
?>
echoisacommandused inPHP todisplayanythingonscreen.
Comments:
• //thisissingle line comment
• #thisisalsosingleline comment
• /*thisismultiline comment,
• canspreadoverthousandsoflines*/
Page|2
Variables
Variableisnamegiventomemorylocationwhosevaluemayvaryduringtheexecutionof
program
Variablesinaprogramareusedtostoresomevaluesordatathatcanbeusedlaterinaprogram.
● 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)
● Avariablenamecanonlycontainalphanumericcharactersandunderscores(i.e., ‘a-z’, ‘A-
Z’, ‘0-9 and ‘_’) in their name. Even it cannot start with a number.
● Assignment of variables is done with the assignment operator, “equal to (=)”. The
variable names are on the left of equal andtheexpressionorvaluesaretotherightof the
assignment operator ‘=’.
Constants
● Aconstantisanidentifier(name)forasimplevalue.Thevaluecannotbechangedduring
the script.
● Avalidconstantnamestartswithaletterorunderscore(no$signbeforetheconstant
name).
Syntax:
define(name,value, case-insensitive)
example:
<!DOCTYPEhtml>
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING","Welcometo!");echo GREETING;
?>
</body>
</html>
Variable Scopes
Scopeofavariableisdefinedasitsextentinprogramwithinwhichitcanbeaccessed,i.e.thescopeofa
variable is the portion of the program within which it is visible or can be accessed.
Page|3
Dependingon the scopes, PHP has threevariablescopes:
Local variables: The variables declared within a function are called local variables to that
function and have its scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with the
same name as that of the one within the function is a completely different variable.
Global variables: The variables declaredoutside a function are called globalvariables.These
variables can be accessed directlyoutsidea function. To getaccess within a function we need
to use the “global” keyword before the variable to refer to the global variable.
Static variable: It is the characteristic of PHP to delete the variable, ones it completes its
execution and the memory is freed. But sometimes we need to store the variables even after
the completion of function execution. To do this we use static keywordandthevariablesare
then called as static variables.PHP associates a data type depending on the value for the
variable.
<?php
function static_var()
{
//staticvariable
static$num=5;
$sum = 2;
$sum++;
$num++;
echo$num,"\n";echo
$sum,"\n";
}
//firstfunctioncall
static_var();
//secondfunctioncall
static_var();
?>
Output:
6
3
7
3
Datatypes
● Datatypesspecifythesizeand typeofvalues thatcanbe stored.
● VariabledoesnotneedtobedeclaredITSDATATYPEaddingavaluetoit.
● PHPisaLooselyTypedLanguagesoherenoneedtodefinedatatype
● Tocheckonlydatatypeusegettype()function.
● Tocheckvalue,data typeand sizeusevar_dump()function.
Page|4
Variousdata type:
● Integers
● Doubles
● NULL
● Strings
● Booleans
● Arrays
● Objects
● Resources
Expressionsandoperators
ThefollowinglistsdescribethedifferentoperatorsusedinPHP.
PHPArithmeticOperators
Thearithmeticoperatorsareusedtoperformcommonarithmeticaloperations,suchasaddition,
subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators:
Operator Description Example Result
+ Addition $x+ $y Sumof$xand $y
- Subtraction $x-$y Differenceof$xand$y.
* Multiplication $x* $y Productof$xand $y.
/ Division $x/ $y Quotient of $xand $y
% Modulus $x% $y Remainderof$xdivided by$y
Example:
<!DOCTYPEhtml>
<html lang="en">
<head>
<title>PHP Arithmetic Operators</title>
</head>
<body>
<?php
$x= 10;
$y = 4;
echo($x+$y);
echo "<br>";
echo($x-$y);
echo "<br>";
echo($x*$y);
Page|5
echo "<br>";
echo($x/$y);
echo "<br>";
echo($x%$y);
?>
</body>
</html>
Output:
14
6
40
2.5
2
PHPAssignmentOperators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
Operator Description Example IsThe SameAs
= Assign $x= $y $x=$y
+= Addandassign $x+=$y $x=$x+$y
-= Subtractand assign $x-=$y $x=$x- $y
*= Multiplyandassign $x*= $y $x=$x* $y
/= Divideandassignquotient $x/= $y $x=$x/$y
%= Divideandassignmodulus $x%= $y $x=$x% $y
Page|6
<html lang="en">
<head>
<title>PHPAssignmentOperators</title>
</head>
<body>
<?php
$x = 10;
echo $x;
echo"<br>";
$x= 20;
$x+=30;
echo $x;
echo"<br>";
$x= 50;
$x-=20;
echo $x;
echo"<br>";
$x= 5;
$x *= 25;
echo $x;
echo"<br>";
$x= 50;
$x /= 10;
echo $x;
echo"<br>";
$x= 100;
$x%=15;
echo$x;
?>
</body>
</html>
Output:
10
50
30
125
5
10
PHPComparisonOperators
ThePHP comparison operators areused tocomparetwo values(numberorstring):
Operator Name Example Result
== Equal $x==$y Trueif$xisequalto$y
Page|7
=== Identical $x===$y Trueif$xisequalto$y,andtheyare
of the same type
!= Not equal $x!=$y Trueif$xisnotequalto$y
<> Not equal $x<>$y Trueif$xisnotequalto$y
!== Not identical $x!==$y Trueif$xisnotequalto$y,orthey are
not of the same type
< Lessthan $x<$y Trueif$xislessthan$y
> Greaterthan $x>$y Trueif$xisgreaterthan$y
>= Greaterthanor equalto $x>=$y Trueif $xisgreaterthanorequalto
$y
<= Lessthanorequal to $x<=$y Trueif$xislessthanorequal to
$y
Example:
<!DOCTYPEhtml>
<html lang="en">
<head>
<title>PHP Comparison Operators</title>
</head>
<body>
<?php
$x= 25;
$y=35;
$z= "25";
var_dump($x == $z);
echo "<br>";
var_dump($x===$z);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x!==$z);
echo "<br>";
var_dump($x < $y);
echo "<br>";
var_dump($x > $y);
echo "<br>";
var_dump($x <= $y);
echo "<br>";
var_dump($x >= $y);
?>
</body>
</html>
Output:
Page|8
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
PHPIncrementingandDecrementingOperators
Theincrement/decrementoperatorsareusedtoincrement/decrementavariable'svalue.
Operator Name Effect
++$x Pre-increment Increments$xbyone,thenreturns$x
$x++ Post-increment Returns$x, then increments $xbyone
--$x Pre-decrement Decrements $xbyone, thenreturns$x
$x-- Post-decrement Returns$x, then decrements $xbyone
Example:
<!DOCTYPEhtml>
<html lang="en">
<head>
<title>PHPIncrementingandDecrementingOperators</title>
</head>
<body>
<?php
$x= 10;echo
++$x;
echo"<br>";
echo
$x;echo"<hr>"
;
$x= 10;echo
$x++;
echo"<br>";
echo
$x;echo"<hr>"
;
$x= 10;echo
Page|9
echo
$x;echo"<hr>"
;
$x= 10;echo
$x--;
echo"<br>";
echo $x;
?>
</body>
Output:
11
11
10
11
9
9
10
9
PHPLogicalOperators
Thelogical operators aretypicallyusedtocombineconditionalstatements.
Operator Name Example Result
and And $xand $y Trueifboth$xand$yaretrue
or Or $xor $y Trueifeither$xor$yistrue
xor Xor $xxor$y Trueifeither$xor$yistrue,butnotboth
&& And $x &&$y Trueifboth$xand$yaretrue
|| Or $x ||$y Trueifeither$$xor$yistrue
! Not !$x Trueif$xisnottrue
Example:
<!DOCTYPEhtml>
<html lang="en">
<head>
<title>PHPLogicalOperators</title>
</head>
<body>
<?php
Page|10
$year=2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year%400==0)||(($year%100!=0)&&($year%4==0))){echo"$year
is a leapyear.";
} else{
echo"$yearisnotaleapyear.";
}
?>
</body>
</html>
Output:
2014is notaleapyear.
PHPStringOperators
Therearetwooperatorswhicharespecificallydesignedforstrings.
Operator Description Example Result
. Concatenation $str1. $str2 Concatenationof $str1 and $str2
.= Concatenationassignment $str1.=$str2 Appendsthe$str2tothe$str1
Example:
<!DOCTYPEhtml>
<html lang="en">
<head>
<title>PHP StringOperators</title>
</head>
<body>
<?php
$x = "Hello";
$y = "World!";
echo$x.$y;//Outputs:HelloWorld!echo
"<br>";
$x.= $y;
echo$x;//Outputs:Hello World!
?>
</body>
</html>
Output:
HelloWorld!
HelloWorld!
Page|11
PHPArrayOperators
Page|12
var_dump($x===$y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x <> $y);
echo "<br>";
var_dump($x!==$y);
?>
</body>
</html>
Output:
array(6){["a"]=>string(3)"Red"["b"]=>string(5)"Green"["c"]=>string(4)"Blue"
["u"]=>string(6)"Yellow"["v"]=>string(6)"Orange"["w"]=>string(4)"Pink"}
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
Page|13
Decisionmakingcontrolstatements
Conditionalstatementsareusedtoperformdifferentactionsbasedondifferentconditions.In
PHP we have the following conditional statements:
● ifstatement-executes some codeifone condition istrue
● if...elsestatement-executessomecodeifaconditionistrueandanothercodeif that
condition is false
● if...elseif...elsestatement-executesdifferentcodesformorethantwoconditions
● switchstatement-selects one of manyblocks ofcode to beexecuted
ifStatement
Theifstatement executessomecode if one condition istrue.
Syntax:
if(condition){
codeto beexecuted ifcondition istrue;
}
Example:
<!DOCTYPEhtml>
<html>
<body>
<?php
$t = date("H");
if($t<"20") {
echo "Havea goodday!";
}
?>
</body>
</html>
Output:
Havea good day!
if...elseStatement
Theif...elsestatementexecutessomecodeifaconditionistrueandanothercodeifthatconditionis
false.
Syntax:
if(condition){
codeto beexecuted ifcondition istrue;
} else {
codeto beexecuted ifcondition isfalse;
}
Example:
<!DOCTYPEhtml>
<html>
Page|14
<body>
<?php
$t = date("H");
if($t<"20") {
echo "Havea goodday!";
} else {
echo "Havea goodnight!";
}
?>
</body>
</html>
Output:
Havea good day!
if...elseif...elseStatement
Theif...elseif...elsestatementexecutesdifferentcodesformorethantwoconditions.Syntax:
if(condition){
codeto be executedifthis condition istrue;
} elseif(condition) {
codeto be executed iffirstcondition is falseand this condition istrue;
} else {
codeto beexecuted if allconditions are false;
}
Example:
<!DOCTYPEhtml>
<html>
<body>
<?php
$t = date("H");
echo"<p>Thehour(oftheserver) is". $t;
echo ",andwillgivethefollowingmessage:</p>";
if($t<"10") {
echo "Havea goodmorning!";
}elseif($t <"20") {
echo "Havea goodday!";
} else {
echo "Havea goodnight!";
}
?>
</body>
</html>
Output:
Page|15
Thehour(oftheserver)is10,andwillgivethefollowingmessage:Havea good
day!
switchStatement
Theswitchstatementisusedtoperformdifferentactionsbasedondifferentconditions.Syntax:
switch (n) {
caselabel1:
codetobeexecutedifn=label1; break;
case label2:
codetobeexecutedifn=label2; break;
case label3:
codetobeexecutedifn=label3; break;
...
default:
codetobeexecutedifnisdifferentfromalllabels;
}
Example:
<!DOCTYPEhtml>
<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,norgreen!";
}
?>
</body>
Page|16
</html>
Output:
Yourfavoritecolorisred!
breakStatement
Sometimesasituationariseswherewe wanttoexitfromaloopimmediatelywithoutwaitingto get
back to the conditional statement.
Thekeywordbreakendsexecutionofthecurrentfor,foreach,while,dowhileorswitchstructure.Whent
hekeywordbreakexecutedinsidealoopthecontrolautomaticallypasses
tothefirststatementoutsidetheloop.Abreakisusuallyassociatedwith the if.
Example:
<?php
$array1=array(100,1100,200,400,900);
$x1=0;
$sum=0
while ($x1<=4)
{
if ($sum>1500)
{
break;
}
$sum = $sum+$array1[$x1];
$x1=$x1+1;
}
echo$sum;
?>
Output:
1800
continueStatement
Sometimes asituation ariseswhere we want to take the control to the beginning of the loop(for
examplefor,while,dowhileetc.)skippingthereststatementsinsidetheloopwhichhave not yet been
executed.
The keywordcontinueallowustodothis.Whenthekeywordcontinueexecutedinsidealoop the
control automatically passes to thebeginningofloop.Continueisusuallyassociatedwith the if.
Example:
<?php
$x=1;echo'Listofoddnumbersbetween1to10<br/>';
while ($x<=10)
{
if(($x % 2)==0)
Page|17
{
$x++;
continue;
}
else
{
echo$x.'<br/>';
$x++;
}
}
?>
Output:
Listofoddnumbersbetween1to101
3
5
7
9
Page|18
Loopcontrolstructure
Loopsareusedtoexecutethesameblockofcodeagainandagain,aslongasacertainconditionistrue.
InPHP,wehavethefollowinglooptypes:
● while- loops through a blockof code as long asthe specified condition is true
● do...while-loopsthroughablockofcodeonce,andthenrepeatstheloopas long
as the specified condition is true
● for- loopsthrough ablockof codea specifiednumberoftimes
● foreach-loopsthroughablockofcodefor eachelementinan array
whileLoop
Thewhileloopexecutesablockofcodeaslongasthespecifiedconditionistrue.Syntax:
while(conditionistrue){code
to be executed;
}
Examples:
<?php
$x= 1;
while($x<=5) {
echo "The numberis: $x<br>";
$x++;
}
?>
Output:
Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5
DowhileLoop
Thedo...whileloopwillalwaysexecutetheblockofcodeonce,itwillthencheckthecondition,and
repeat the loop while the specified condition is true.
Syntax:
do {
codeto beexecuted;
}while (condition is true);
Examples:
<?php
$x=1;
do {
echo"Thenumberis:$x <br>";
Page|19
$x++;
} while ($x<=5);
?>
Output:
Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5
forLoop
Theforloopisusedwhenyouknowinadvancehowmanytimesthescriptshouldrun.Syntax:
for(initcounter;testcounter;incrementcounter){
codetobe executedfor each iteration;
}
Parameters:
● init counter:Initializetheloopcounter value
● testcounter:Evaluatedforeachloopiteration.IfitevaluatestoTRUE,theloop
continues. If it evaluates to FALSE, the loop ends.
● incrementcounter:Increasestheloopcountervalue
Example:
<?php
for($x=0;$x<=10;$x++){
echo"Thenumberis:$x<br>";
}
?>
Output:
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 numberis:10
Page|20
ForeachLoop
Theforeachloopworksonlyonarrays,andisusedtoloopthrougheachkey/valuepairinanarray.
Syntax:
foreach($arrayas$value){
code to be executed;
}
Example:
<?php
$colors=array("red","green","blue","yellow");
foreach($colorsas$value){
echo "$value <br>";
}
?>
Output:
red
green
blue
yellow
Page|21