0 ratings0% found this document useful (0 votes) 19 views10 pagesConditional Statement PHP
One of the
Statement in php
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Har 7 THE BASICS OF PHP =
PAGE 309
Iso be identifi
pray stots can @ identified by name. These 4
At ype of aray with one major Cierence led Associative a
FETT a eth og rays. They are identical to any Lo
infassociative arrays, index values are not fi
W tgang anid Working with Associative Fea sean als eee eae
: .
Dring example makes the code spe mor eae calf working with any athe ype of ary. The
fay 8 follows: asy to understand by the use of associative
J) $personal_datal first name'] = Ivan’;
$personal_data["post"] = ‘Professor’;
$personal_data['last name'] = "Bayross';
$personal_data[‘age"] = 65; :
echo "Hi". $personal_dataf'first name]
| We know that you are ' . $personal_dataf'age'] . ' years old."
‘he PHP parser will ignore all whitespace and the result ist
o
(Hi ivan!_We know that you are 65 years old. ]
This is often the easiest way to deal with associative arrays, Another possiblity is to use variable
substitution with curly braces like this
‘echo "Hi {$personal_datap first name"}}! |
"We know that you are {$personal_dataf'age'J} years0ld.";
‘This code gives the same result. More complex expressioys can be used inside such a set of curly braces.
This includes accessing elements in multidimensional arrays and object properties.
ped
Tinrecommended to use descriptive names forthe slots in the arays. It makes the code spec ‘lear
and helps to indicate what the different slots are intended for
CONDITIONAL STATEMENTS
Z The linear, hierarchic, top down, execution of a program, is controlled by ‘Control Structures! embedded
within program code. PHP code often has 10 do several things, this means that PHP code has to have
within oa a aolites, based on the decision made, the PHP code will do seme work or otherwise do
sec oraz else entirely, PHP provides programmers with conditional statements to-achieve this.
‘There are two types of conditional statements:
if (uels) statement - Ths statement is used, if = Block of code must test a specific condition, if the
Met teeted returns a "TRUE then the code executes, If the condition tested returns "FALSE!
another block of code executes
switch statement - This statement is used to choose and execute one code block from among multiple
code blocks for execution
The if Statement
if statements are the most common conditional statements and they exist in most
Uae the if-tatement to exccute different code snippets of PHP code ina program,
(je. either TRUE or FALSE) when a condition is evaluated.”
programming languages.
based on what is retunedPAGE 310 CWAD USING HTML, JAVASCRIPT, DHTML AND PHP CHAP 47
Syntax:
If (Conaieion) :
|
Output: (As shown in diagram 17.15)
eras
inaget~ @ vdomatin* ) Mecelaneous” 47 Cutie” $3 Rese
Both the strings are equal
Diagram 17.15
In the above example, there are two variables i.e. str and str2 holding th he ste holding
value Hi is equal to the value of str2 then appropriate message is doh deol ge Mines
Executing Multiple Statements
Example:
When multiple lines of code require execution, when a condition i ‘ enclos
Woe iy Packs, ibe he ovina en TRUE, these lines should be
! ) -quar 17 ‘THE BASICS OF PHP PAGE 31t
<2phP
gmonth = date("M");
if ($month = "Oct")
(cee
| copy Starting” the cede Brock’ oo ”
"echo "The month is October
";
echo "Its Diwali";
cE fending the coda brsek 707"
7 Ee ae
I SEREETRG HE ESeES.
“echo "The mont!
Output: (As shown in diagram 17.16.1 and diagram 17.16.2)
‘The month i October
Wis Dee
Diagram 17.162: Multr-line output when
the condition is not satisfied
Diagram 17.16.1: Multi-line ‘output when
‘the condition is satisfied .
In the above example, the current ‘month is assigned to the variable ‘Smonth, then a check is made as to
the current month is October). When the month is
aoa atvariable Smonth holds value Oct (+, whether month i
dreater, theif statement returns TRUE. This “lows the code block immediately following the If statement
tobe executed
If any other month is assigned to Smonth, the if statement retums FALSE. This eauses the code block
ay ely following the else statement 10 Be executed.
However, as multiple statements have 10 BE executed, the if else statements are followed by opening curly
tee indicating the stat of the code block) “The statements that should be executed are placed after the
asc curly braces. Finally, the closing oly braces } (indicating the end of the code block) are placed
‘The pair of curly braces (} after the condition, conaing tt code block that should be executed when
The ai ot sgun TRUE, Similarly, the pair of curly braces {} afer the else clus ins the
‘hat should be executed when the condition retorns FALSE, : ore amet
‘All kinds of statements can be used between the parenthesis and the curt is
¥ braces. PHP is a language where
‘imost every statement has a value. A v ; fd
as flue can be used together with other values to build complexPAGE 312 CWAD USING HTML, JAVASCRIPT: DHTML AND PHP CHAP 17
cates that Sb now holds the value held by gy
Take an assignment for example. The statement $b = $a, indi Tike th
i
This means that this bbe user
$= ($b = $a);
‘The assignment in the parenthesis has the value of $A
actually be dropped and the result will be the same, AN |
the following statements
‘shich is then assigned to Se. The parenthesis cy
yore variables have the value of $a, Ths explain
/* initializing counters: */
Siz $= $k=S1=0; ]
Using comparison operators any kind of Boolean expression can be constructed. Take for example te
following if statements
if ($a <= $b && ($array[$a] <= $array($b] I $array($a+$b] > $array[$2-$b]))
paTisis a comment, ewonielbe meauted 7
“This if statement, first tests to see iff the value held by variable $a is smaller or equal to the value held by
Variable Sb. If TRUE, the first part of the second section ( after the &&) is executed to see if its also
TRUE. This happens because the && is being used, which means that the first section and the second
section should both be TRUE.
“The first part ofthe second section (ie after the &&) uses $a and Sb as indices in an array. Ifthe first pr
ofthe second section (i. after the &&) is TRUE, then the second part of the second section, (ie. afer the
[p will not be executed. This happens because the || is being ‘used, which means either of the parts in the
second section need to be TRUE.
The following statement illustrates the same:
maysql_connect() or die(‘Could not connect to the MySQL databasel’); ]
‘The function mysql_connect tries to connect to @ MySQL database engine. This returns TRUE ifitis
able to make a connection, PHP evaluates the line as a Boolean expression, That means it starts ty
executing mysql_connect(. If that retums TRUE then PHP skips the next statement because the oF w
operator is used. If the first statement fails, the second statement is executed which halts progat
processing with the user defined error message.
The elseif Clause
The elseif construct can be used to conduct a series of conditional checks and only execute the oe
following the first condition that is met. The last elseif could bi i Sum
not negative and not zero, it must be positive. te ee
Consider the following code:
‘
}
>
x
y
+
else { print "It is December." 3
yo PP RPEEH YF
>
The objective of the above code is to identify the current month of the machine serving PHP pages. The
technique used is a very crude manvaer of working withthe nested if statements.
“The code block starts by extracting the month and storing it into the variable Sm. A check is made if the
extracted month is January. If the condition retums TRUE, @ message indicates that the month is
‘January. Ifthe condition returns FALSE, the code block specified under the else clause is executed.
‘The code block under the else clause consist of @ nested if statement. This if statement checks whether the
re ped month is February. Depending on the value returned by the condition, an appropriate code block
saareeuted (Le. either a message indicating the month or an else clause).
The code block for the inner else clause is ancther set of if statements. Thus the level of nested if
statements increases to check forall possible values for the variable $m.
‘The end result is a code, which is difficult to manage, basicaly because PHP insists that every code block
beginning with an opening curly brace be terminated with a closing curly brace.
‘Another method for achieving the same functionality is the use of the elseif clause. The elseif clause allows |
‘working with nested if statements ina slightly more intelligent way.
Syntax: i
if ()
Seoae Block To Be Executed If (Condition Returns TRUE);
elseif () |
“Code Block To Be Executed If
else
‘
";
if (si
t
+
elseif ($m=="Feb")
t
an")
print "It is January.";
print "It is February.";
}
elseif ($m=="Mar")
t
print "It is March.";
t
elseif (m=="Apr")
print "It is April."
+
elseif ($m=
t
print "It i
3
elseif ($m=:
print "It is June."; ei
elseif ($m=="Jul")
print "It is July."
}
elseif ($1 ‘Aug")
t
print "It is August.";
‘Sep")
+
elseif ($m:
£
print "It is September.";
+
el
{
if ($m=="0ct")
print "It is October.";
?
elseif ($m=="Nov")
print "It is Novémber.";
+
else
CHAP 47e
yet THE BASICS OF
on Pim, PAGE 315
print "It is December
}
2
pats (As shown in diagram 17.17)
yi
| ove Cotes) 655- ] Fame ones @ teat
kis October,
Diagram 17.17
“Tra braves could be avoided if only one line of code To be executed for a condition. Even thous
Thee is only the tiniest fraction of a speed difference ve ween using braces and not using braces. its
r
usually down to a readability issue
‘The same effect can be achieved by having lots of if statements as shown below:
print "It is January.";
print “It is February:"7
print “It is March.”
print “It is April
print "It is May."
print "It is June."
print "It is July."
print "It is August."7
print "It is September."7
print "It is Octobe
print “It is November.";
print "It is December
AAA AAA AAA AA
ferent
However, the use of the elseif clause is slightly neater way of working with neste s.
ie side ofthis system is thatthe $m variable needs to be checked ) ee
‘The switch Statement
‘The switch statement is usually used to elegantly replace lengthy if/ else
lengthy if / elseif statements. Swit
The 7p contol program flow by testing a single variable against multiple values, _—
/
\HP cHar
PAGE 316 CWAD USING HTML, JAVASCRIPT, OHTML AND PI P47
advisable to use the switch statement,
possible values it
for execution).
jon is then compared to all possible case
block placed under that particular case
tof the explicit break; mentioned in
When the same variable is checked for different
(ie. ifonly one of many code blocks have to be selected f
The switch statement is given an expression, This expresso
expressions listed in its body. On a successful match, the vee
expression is exccuted, alter which the code spec terminates Dee
each case section,
De
The match is done inemally using the regular equality operator (==) and not the identical operator
Oo)
Syntax:
‘switch ()
t
case t :
;
break;
case ?
;
break;
default:
‘ltitie To Be Executed If Expression Is Different From Both Labell
And tabel2>}
3
In Switch statement, the ease keyword is a label as it marks’a point in the code to do something.
Specifically it marks the point in the code to begin executing statements if the value of the expression being
evaluated by the switch statement is equal to the value immediately following the case keyword or if the
expression following the case keyword evaluates to TRUE. The colon marks the end of the label. The
entire label should be on one line.
Since expressions are allowed in case labels, other conditions can also be tested, such as greater than and
less than relationships. When using expressions, the expression used for testing against must be repeated i
the case statement.
—————————————
If an expression successfully evaluates to the values specified in more than one case statement, oal¥
the first one encountered will e
ae in untered will be executed. Just after a match is made, PHP stops looking for mort
In switch statement the default keyword is a catch-all
of the conditions being tested for are met. It is similar to
me
ase that marks the point to begin execution of no
the last else statement in a long elseif code block
The default keyword should atways a
PE peed caenhe hie ea at the end of the switch statement, since it will alwayset ‘THE BASICS OF PHP Peet
ampirwing code spec obta °
follow ec obtains the functionali
ee fonality of the nested if statements, by using the switch
Zapp
‘sm=date("M"); j
switch ($m) {
t
case "Jan"
print "It is January.";
case "Feb"
print “It is February.";
break;
case "Mar’
rint "It is March.
break; *
case "Apr":
print “It is April."
break;
case "May"?
print "It is May."7
break;
case "Jun"
print “It is June.";
break;
case "Jul
print "It is July."7
break;
case "Aug
print
break;
case "Sep
print "It is september."
break;
it is August."
"Oct"
print “It is October."
case "Nov"?
print “itis November."
break;
case "Dec":
print “It is December.";
break;
defauli
print "None of the months are valid.";| Pp cl 1
PAGE 318 CWAD USING HTML, JAVASCRIPT, HTML ‘AND PH HAP 17
‘Output: (Refer to diagram 17.18)
| Say
fle Edt Yew History Bookmarks Tools Heb
| GIES? SX: ait (A ie tmns - a :
{© oatle» & cookies 1.C5S+ EJ Forms [i unags = @ reformation” Cp vsataens of Ofte 2s ie eT
| Sia
Diagram 17.18
“The code block starts by extracting the month and storing it into the variable $m. A check is made to
identify the value stored in Sm, When the first case clause is encountered and the value stored in the
eerie matches the value following the case keyword (inthis case ‘Nov’, the block of ‘code immediately
after the first ease clause is executed.
If there is no match, the control is directly passed to the next ease clause. The code block placed betwees
the failed ease clause and the next are ignored: If all case clauses fail, the code block under the default
clause gets executed.
Sometimes, itis possible that the argument in a switeh statement satisfy two of more conditions. In such
Situations, the break keyword is used to restrict PHP from execution of all case clauses having their
Conditions satisfied. When the control comes across the break keyword, the remaining code block held
‘within the condition gets ignored and the control is placed on the next statement,
PHP offers an alternative syntax for some of its control structure:
form of the alternate syntax is to change the opening brace to a colon
endswiteh; respectively.
and switch. In each case, the basi
and the closing brace to endif of
Example:
‘
str is equal to Hello World
“Hello World"):
| eget ear kW wi mane
iyed only if $str is equal to Hello World.
M aa