Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu PHP and MySQL by Example- P5 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.81 MB, 50 trang )

Explanation
!
"#$%G"]^%&0(<%')%)*.(*$-%#$($4%I*)%.3*'0,%3.++)%*#$%)3('6*%form.php4
5
"#$%FGF%)3('6*%')%)*.(*$-%#$($4%I*%:'++%6(03$))%*#$%&0(<%',67*4
P
I&%*#$%&0(<%#.)%2$$,%)72<'**$-8%*#$%1.+7$%$_POST['submit']%:'++%2$%)$*4
Q
"#$%$_POST%.((.=%30,*.',)%*#$%*$9*%*#.*%*#$%7)$(%*=6$-%',%*#$%*$9*%.($.%2098%
,.<$-%story4%JB$$%S#.6*$(%!\8%L]0($%0,%FGF%C0(<)8M%&0(%<0($%',&0(<.*'0,%0,%
*#$%$_POST%.((.=4K%C0(%,0:8%$input%30,*.',)%*#$%',67*%*=6$-%2=%*#$%7)$(4%B$$%
C'/7($%D4PD4
b
"#$%stripslashes()%&7,3*'0,%($<01$)%*#$%)+.)#$)%*#.*%:$($% $-%2=%
addslashes()8%*#$%-$&.7+*%2$#.1'0(%:#$,%*#$%magic_quotes_gpc%-'($3*'1$%#.)%
2$$,%*7(,$-%0,%',%*#$%php.ini%&'+$4
%
Figure 6.36. The user fills in a form.



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 6.37. After the form in Figure 6.36 is submitted. Output of Example 6.36.
%
%
%
6.2.15. Working with HTML Special Characters
Like all languages, HTML has certain characters that have special significance and those characters are represented by
HTML entities, special symbols starting with an ampersand and terminated with a semicolon; for example, the < and >
symbols are written as &lt; and &gt;. If the user enters text that contains these HTML characters (see Table 6.14)
when filling out a form, you can use the htmlspecialchars() function to convert the most common special


characters to their respective HTML entities. If you require all HTML character entities to be translated, use
htmlentities() shown in the next section.
Table 6.14. HTML Special Character Functions
Function
What+It+Does
htmlspecialchars_decode()
S0,1$(*)%)6$3'.+%G"]^%$,*'*'$)%2.3A%*0%3#.(. 3*$()
htmlspecialchars()
S0,1$(*)%)6$3'.+%3#.(.3*$()%*0%G"]^%$,*'*'$)
%
The htmlspecialchars() Function
The htmlspecialchars() function converts special characters (shown in Table 6.15) to HTML entities.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.



Table 6.15. Conversion of Special Characters
Character+Before
The+HTML+Entity
&%J.<6$().,-K
&amp;
"%J-072+$%;70*$K
&quot;%:#$,%ENT_NOQUOTES%')%,0*%)$*
'%J)',/+$%;70*$K
&#039;%0,+=%:#$,%ENT_QUOTES%')%)$*
<%J+$))%*#.,K
&lt;
>%J/($.*$(%*#.,K
&gt;
%

Format
string htmlspecialchars (string string [, int quote_style [,
string charset]])
%
Example:
$text = "Isn't the << symbol is used in here-docs?"; echo
htmlspecialchars($text, ENT_QUOTES), "<br />";

You can define how to handle single or double quotes using the quote_style optional third argument, and define
the character set for your locale by using the optional fourth argument, called charset. Quote constants are shown in
Table 6.16.
Table 6.16. Quote Constants
Constant+Name
Description
ENT_COMPAT
S0,1$(*)%-072+$%;70*$)%.,-%+$.1$)%)',/+$%;70*$)%.+0,$8%*#$%-$&.7+*%<0-$
ENT_QUOTES
S0,1$(*)%20*#%-072+$%.,-%)',/+$%;70*$)
ENT_NOQUOTES
^$.1$)%20*#%-072+$%.,-%)',/+$%;70*$)%7, 30, 1$(*$-
%
Example 6.37 demonstrates how to use the htmlspecialchars() function. The output can be viewed in Figure
6.38.
Example 6.37.
<html><head><title>The htmlspecialchars() Function</title>
</head>
<body bgcolor="lavender">
<font size="+1">
<h3>Creating HTML Entities</h3>
<b>

<?php
1 $text = "<<Johnson&Son's Tobacco Store>>";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2 echo "Original: $text<br /><br />";
3 echo "Modified: ", htmlspecialchars($text), "<br />";
?>
</b>
</body>
</html>
Explanation
!
"#$%1.('.2+$8%$text8%')%.))'/,$-%.%)*(',/%30,*.',',/%)0<$%3#.(.3*$()%
30,)'-$($-%)6$3'.+%:#$,%($,-$($-%2=%*#$%G"]^%',*$(6($*$(@%*#$=%.($%*#$%<%.,-%
&%3#.(.3*$()4
5
?#$,%*#')%)*(',/%')%1'$:$-%',%*#$%2(0:)$(8%*#$%G"]^%',*$(6($*$(%)$$)%*#$%<%.)%
.,%06$,',/%*./%)=<20+%&0++0:$-%2=%.,%'(($+$1.,*%G"]^%$+$<$,*4%Y0*#',/%')%
-')6+.=$-%0*#$(%*#.,%*#$%,$9*%06$,',/%<%.,-%*#$%3+0)',/%>4
P
"#$%htmlspecialchars()%&7,3*'0,%3($.*$)%G"]^%$,*'*'$)%07*%0&%*#$%<%.,-%&%)0%
*#.*%*#$%2(0:)$(%3.,%-')6+.=%*$9*4%Y0*$%*#.*%*#$%)07(3$%6./$%J)$$%C'/7($%D4PcK%
&0(%*#$%?$2%6./$%)#0:)%*#.*%*#$)$%$,*'*'*'$)% . ($%,0:%6.(*%0&%*#$%6./$4

Figure 6.38. Converting special characters to HTML entities. Output from Example 6.37.

%








Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 6.39. Viewing the source page in the browser.
%
%
%
The htmlentities() Function
The htmlentities() function converts all applicable characters to their HTML entities equivalents.
Format
string htmlentities (string string [, int quote_style [,
string charset]])
%
Example:
$string = "5¢ won't get you much at the café Française!"; echo
htmlentities($string, ENT_COMPAT); // Returns: 5&#162 won't get you much at the
caf&egrave;
Fran&ccedil;aise!

Table 6.17. Supported Character Sets
Charset
Aliases
Description
IBUO[[bcO
!
IBU[[bcO!
?$)*$(,%_7(06$.,8%^.*',O!4
IBUO[[bcO
!b

IBU[[bcO!b
?$)*$(,%_7(06$.,8%^.*',Oc4%W )%*#$%_7(0%)'/,8%C($,3#%
.,-%C',,')#%+$**$()%<'))',/%',%^.*',O!%JIBUO[[bcO!K4
X"CO[
%
WBSIIO30<6.*'2+$%<7+*'2=*$%[O2'*%X,'30-$4
36[DD
'2<[DD8%[DD
VUBO)6$3'&'3%S=('++'3%3#.()$*4%"#')%3#.()$*%')%)7660(*$-%',%
Q4P454
36!5b!
?',-0:)O!5b!8%
:',O!5b!8%!5b!
?',-0:)O)6$3'&'3%S=('++'3%3#.()$*4%"#')%3#.()$*%')%
)7660(*$-%',%Q4P454
36!5b5
?',-0:)O!5b58%
?',-0:)O)6$3'&'3%3#.()$*%&0(%?$)*$(,%_7(06$4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.17. Supported Character Sets
Charset
Aliases
Description
!5b5
mUI[O`
A0'[O(78%A0'[(
`7))'.,4%"#')%3#.()$*%')%)7660(*$-%',%Q4P454
>Inb
cb\
"( '*'0,.+%S#',$)$8%<.',+=%7)$-%',%".':.,4

n>5P!5
cPD
B'<6+'&'$-%S#',$)$8%,.*'0,.+%)*., (-%3#.(.3*$(%)$*4
>InbO
GmBSB
%
>'/b%:'*#%G0,/%m0,/%$9*$,)'0,)8%"( '*'0,.+%S#',$)$4
B#'&*ehIB
BhIB8%cP5
h.6.,$)$4
_XSOhF
_XShF
h.6.,$)$4
6.3. Other String Functions
This chapter focused on some of the most useful string functions, but PHP provides other useful string functions, as
shown in Table 6.18.
Table 6.18. PHP Functions
Function
What+It+Does
addcslashes
l70*$)%)*(',/%:'*#%)+.)#$)%',%.%S%)*=+$4
addslashes
l70*$)%)*(',/%:'*#%)+.)#$)4
bin2hex
S0,1$(*)%2',.(=% *.%',*0%#$9 $3'<.+%($6($)$,*.*'0,4
chop
W+'.)%0&%rtrim()4
chr
`$*7(,)%.%)6$3'&'3%3#.(.3*$(4
chunk_split

B6+'*)%.%)*(',/%',*0%)<.++$(%3#7,A)4
convert_cyr_string
S0,1$(*)%&(0<%0,$%S=('++'3%3#.(.3*$(%)$*%*0%.,0*#$(4
convert_uudecode
V$30-$)%.%77$,30-$-%)*(',/4
convert_uuencode
X7$,30-$)%.%)*(',/4
count_chars
`$*7(,)%',&0(<.*'0,%.207*%3#.(.3*$()%7)$-%',%.%)*(',/4
crc32
S.+37+.*$)%*#$%3(3P5%60+=,0<'.+%0&%.%)*(',/4
crypt
U,$O:.=%)*(',/%$,3(=6*'0,%J#.)#',/K4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.18. PHP Functions
Function
What+It+Does
echo
U7*67*)%0,$%0(%<0($%)*(',/)4
explode
B6+'*)%.%)*(',/%2=%)*(',/4
fprintf
?('*$)%.%&0(<.**$-%)*(',/%*0%.%)*($.<4
get_html_translation_table
`$*7(,)%*#$%*(.,)+.*'0,%*.2+$%7)$-%2=%htmlspecialchars()%
.,-%htmlentities()4
hebrev
S0,1$(*)%+0/'3.+%G$2($:%*$9*%*0%1')7.+% *$9*4
hebrevc
S0,1$(*)%+0/'3.+%G$2($:%*$9*%*0%1')7.+% *$9*%:'*#%,$:+',$%

30,1$()'0,4
html_entity_decode
S0,1$(*)%.++%G"]^%$,*'*'$)%*0%*#$'(%.66+'3.2+$%3#. (. 3*$()4
htmlentities
S0,1$(*)%.++%.66+'3.2+$%3#.(.3*$()%*0% G"]^%$,*'*'$)4
htmlspecialchars_decode
S0,1$(*)%)6$3'.+%G"]^%$,*'*'$)%2.3A%*0%3#.(. 3*$()4
htmlspecialchars
S0,1$(*)%)6$3'.+%3#.(.3*$()%*0%G"]^%$,*'*'$)4
implode
h0',)%.((.=%$+$<$,*)%:'*#%.%)*(',/4
join
W+'.)%0&%implode()4
levenshtein
S.+37+.*$)%^$1$,)#*$',%-')*.,3$%2$*:$$,%* :0%)*(',/)4
localeconv
n$*)%,7<$('3%&0(<.**',/%',&0(<.*'0,4
ltrim
B*('6)%:#'*$)6.3$%J0(%0*#$(%3#.(.3*$()K%&(0<%*#$%2$/',,',/%
0&%.%)*(',/4
md5_file
S.+37+.*$)%*#$%md5%#.)#%0&%.%/'1$,%&'+$4
md5
S.+37+.*$)%*#$%md5%#.)#%0&%.%)*(',/4
metaphone
S.+37+.*$)%*#$%<$*.6#0,$%A$=%0&%.%)*(',/4
money_format
C0(<.*)%.%,7<2$(%.)%.%37(($,3=%)*(',/4
nl_langinfo
l7$(=%+.,/7./$%.,-%+03.+$%',&0(<.*'0,4

nl2br
I,)$(*)%G"]^%+',$%2($.A)%2$&0($%.++%,$:+',$)%',%.%)*(',/4
number_format
C0(<.*)%.%,7<2$(%:'*#%/(076$-%*#07).,-)4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.18. PHP Functions
Function
What+It+Does
ord
`$*7(,)%WBSII%1.+7$%0&%3#.(.3*$(4
parse_str
F.()$)%*#$%)*(',/%',*0%1.('.2+$)4
print
U7*67*)%.%)*(',/4
printf
U7*67*)%.%&0(<.**$-%)*(',/4
quoted_printable_decode
S0,1$(*)%.%;70*$-O6(',*.2+$%)*(',/%*0%.,%[O2'*%)*(',/4
quotemeta
l70*$)%<$*.3#.(.3*$()4
rtrim
B*('6)%:#'*$)6.3$%J0(%0*#$(%3#.(.3*$()K%&(0<%*#$%$,-%0&%.%
)*(',/4
setlocale
B$*)%+03.+$%',&0(<.*'0,4
sha1_file
S.+37+.*$)%*#$%sha1%#.)#%0&%.%&'+$4
sha1
S.+37+.*$)%*#$%sha1%#.)#%0&%.%)*(',/4
similar_text

S.+37+.*$)%*#$%)'<'+.('*=%2$*:$$,%*:0%)*(',/)4
soundex
S.+37+.*$)%*#$%)07,-$9%A$=%0&%.%)*(',/ 4
sprintf
`$*7(,)%.%&0(<.**$-%)*(',/4
sscanf
F.()$)%',67*%&(0<%.%)*(',/%.330(-',/%*0%.%&0(<.*4
str_ireplace
S.)$O',)$,)'*'1$%1$()'0,%0&%str_replace()4
str_pad
F )%.%)*(',/%*0%.%3$(*.',%+$,/*#%:'*#%.,0*#$(%)*(',/4
str_repeat
`$6$.*)%.%)*(',/4
str_replace
`$6+.3$)%.++%0337(($,3$)%0&%*#$%)$.(3#%)*(',/%:'*#%*#$%
($6+.3$<$,*%)*(',/4
str_rot13
F$(&0(<)%*#$%(0*!P%$,30-',/%0,%.%)*(',/4%B#'&*)%$1$(=%.+6#.%
3#.(.3*$(%!P%6+.3$)%',%*#$%.+6#.2$*4
str_shuffle
`.,-0<+=%)#7&&+$)%.%)*(',/4
str_split
S0,1$(*)%.%)*(',/%*0%.,%.((.=4
str_word_count
`$*7(,)%',&0(<.*'0,%.207*%:0(-)%7)$-%',%.%)*(',/4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.18. PHP Functions
Function
What+It+Does
strcasecmp

>',.(=O).&$%3.)$O',)$,)'*'1$%)*(',/%30<6.(')0,4
strchr
W+'.)%0&%strstr()4
strcmp
>',.(=O).&$%)*(',/%30<6.(')0,4
strcoll
^03.+$O2.)$-%)*(',/%30<6.(')0,4
strcspn
C',-)%+$,/*#%0&%','*'.+%)$/<$,*%,0*%<.*3#',/%<.)A4
strip_tags
B*('6)%G"]^%.,-%FGF%*./)%&(0<%.%)*(',/4
stripcslashes
X,;70*$)%)*(',/%;70*$-%:'*#%addcslashes()4
stripos
C',-)%60)'*'0,%0&%&'()*%0337(($,3$%0&%.%3.)$O',)$,)'*'1$%)*(',/4
stripslashes
X,;70*$)%)*(',/%;70*$-%:'*#%addslashes()4
stristr
S.)$O',)$,)'*'1$%strstr()4
strlen
n$*)%)*(',/%+$,/*#4
strnatcasecmp
S.)$O',)$,)'*'1$%)*(',/%30<6.(')0,)%7)',/%.%L,.*7(.+%0(-$(M%
.+/0('*#<4
strnatcmp
B*(',/%30<6.(')0,)%7)',/%.%L,.*7(.+%0(-$(M%.+/0('*#<4
strncasecmp
>',.(=O).&$%3.)$O',)$,)'*'1$%)*(',/%30<6.(')0,%0&%*#$%&'()*%,%
3#.(.3*$()4
strncmp

>',.(=O).&$%)*(',/%30<6.(')0,%0&%*#$%&'()*%,%3#.(.3*$()4
strpbrk
B$.(3#$)%.%)*(',/%&0(%.,=%0&%.%)$*%0&%3#.(.3*$()4
strpos
C',-)%60)'*'0,%0&%&'()*%0337(($,3$%0&%.%)*(',/4
strrchr
C',-)%*#$%+.)*%0337(($,3$%0&%.%3#.(.3*$(%',%. % )*(',/4
strrev
`$1$()$)%.%)*(',/4
strripos
C',-)%60)'*'0,%0&%+.)*%0337(($,3$%0&%.%3.)$O',)$,)'*'1$%)*(',/%
',%.%)*(',/4
strrpos
C',-)%60)'*'0,%0&%+.)*%0337(($,3$%0&%.%3#.(.3*$(% ', %.%)*(',/4
strspn
C',-)%+$,/*#%0&%','*'.+%)$/<$,*%<.*3#',/%<.)A4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.18. PHP Functions
Function
What+It+Does
strstr
C',-)%&'()*%0337(($,3$%0&%.%)*(',/4
strtok
"0A$,'a$)%)*(',/4
strtolower
].A$)%.%)*(',/%+0:$(3.)$4
strtoupper
].A$)%.%)*(',/%766$(3.)$4
strtr
"(.,)+.*$)%3$(*.',%3#.(.3*$()4

substr_compare
>',.(=O).&$%06*'0,.++=%3.)$O',)$,)'*'1$%30<6.(')0,%0&%*:0%
)*(',/)%&(0<%.,%0&&)$*8%76%*0%+$,/*#%3#.(.3*$()4
substr_count
S07,*)%*#$%,7<2$(%0&%)72)*(',/%0337(($,3$)4
substr_replace
`$6+.3$)%*$9*%:'*#',%.%60(*'0,%0&%.%)*(',/4
substr
`$*7(,)%6.(*%0&%.%)*(',/4
trim
B*('6)%:#'*$)6.3$%J0(%0*#$(%3#.(.3*$()K%&(0<%*#$%2$/',,',/%
.,-%$,-%0&%.%)*(',/4
ucfirst
].A$)%.%)*(',/H)%&'()*%3#.(.3*$(%766$(3.)$4
ucwords
X66$(3.)$)%*#$%&'()*%3#.(.3*$(%0&%$.3#%:0(-%',%.%)*(',/4
vfprintf
?('*$)%.%&0(<.**$-%)*(',/%*0%.%)*($.<4
vprintf
U7*67*)%.%&0(<.**$-%)*(',/4
vsprintf
`$*7(,)%.%&0(<.**$-%)*(',/4
wordwrap
?(.6)%.%)*(',/%*0%.%/'1$,%,7<2$(%0&%3#.(.3*$()%7)',/%.%)*(',/%
2($.A%3#.(.3*$(4
6.4. Chapter Summary
6.4.1. What You Should Know
Now that you have finished this chapter you should be able to answer the following questions:
1.
?#.*%')%.%)*(',/g

2.
?#$,%-0%=07%7)$%-072+$%;70*$)%0(%)',/+$%;70*$)g
3.
?#.*%.($%$)3.6$%3#.(.3*$()g
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
4.
V$&',$%:#'*$)6.3$4
5.
?#.*%&7,3*'0,)%+$*%=07%&0(<.*%)*(',/)g
6.
G0:%3.,%=07%/$*%*#$%+$,/*#%0&%.%)* (',/%.,-%307,*%*#$%3#.(.3*$()%',%.%)72 )*(',/g
7.
?#.*%&7,3*'0,)%30<6.($%)*(',/)g%W($%)*(',/)%3.)$%)$,)'*'1$%:#$,%*#$=%.($%
30<6.($-g
8.
?#.*%&7,3*'0,)%&',-%)'<'+.('*'$)%',%)*(',/)g
9.
G0:%-0%=07%&',-%.%60)'*'0,%',%.%)*(',/g %?#.*%&7,3*'0,)%+$*%=07%&',-%.%)6$3'&'$-%
60)'*'0,%',%.%)*(',/g
10.
?#.*%')%.%)72)*(',/g%?#.*%&7,3*'0,)%$9*(.3*%6.(*)%0&%.% )*(',/g
11.
?#.*%')%<$.,*%2=%L*('<<',/M%.,-%L6 ',/Mg
12.
?#.*%&7,3*'0,)%.($%7)$-%&0(%)$.(3#',/%.,-%($6+.3',/%:'*#',%)*(',/)g
13.
?#.*%.($%)6$3'.+%3#.(.3*$()g
14.
?#.*%.($%G"]^%$,*'*'$)g
15.

G0:%-0%=07%&0(3$%2($.A)%',%.%)*(',/g
16.
?#.*%&7,3*'0,)%-$.+%:'*#%#0<06#0,$)g
6.4.2. What’s Next?
Chapter 7, “Conditionals and Loops,” covers PHP conditional statements (if/else/elseif, switch) and loops
(while, for, foreach).
Chapter 6 Lab
1.
W))'/,%=07(%$O<.'+% ($))%*0%.%)*(',/4%X)$%FGF%)*(',/%&7,3*'0,)%*0%/$*%*#$%7 )$(%
,.<$%.,-%*#$%-0<.',%,.<$4
2.
S($.*$%*#$%&0++0:',/%)*(',/E%%
$string = " mary jones lives in santa cruz, california at 22 ocean
drive."
%
a. Find the number of characters in the string.
b. Capitalize all the letters in the string.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
c. Now make all the characters lowercase.
d. Use the substr() function to print Santa Cruz, California. The first letter in each
word will be in uppercase.
e. Use the substr() function to print Mary’s street address.
f. Trim out the whitespace at the beginning of the string.
g. Find the index position of California.
h. Replace Santa Cruz with Los Altos (case insensitive).
i. Find the number of words in the string.
3.
X)$%*#$%strcmp()%&7,3*'0,%*0%30<6.($%*#$%&0++0:',/%*:0%)*(',/)8%&'()*%30<6.(',/%
$str1%.,-%$str28%*#$,%30<6.(',/%$str2%.,-%$str14%_96+.',%*#$%1.+7$%*#.*%')%
($*7(,$-%&(0<%*#$%&7,3*'0,4%%

$str1="Pear"; $str2="Pearson";
%
What value is returned from strcmp() if you compare $str1 to $str1?
4.
?('*$%.%)3('6*%*0%/$,$(.*$%.%QO+$**$(%(.,-0<%6.)):0(-%:'*#%766$(3.)$8%+0:$(3.)$8%
.,-%,7<$('3%3#.(.3*$()4%B*0($%*#$%6.)):0(-%.)%.%1.('.2+$%.,-%-')6+.=%'*4B*.(*%:'*#E%%
$str =
"abcdefghijklmnopqrlsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
%
Hint: Try str_shuffle().
5.
S($.*$%.%)3.+.(%1.('.2+$%*0%30,*.',%.%<0,$=%.<07,*%0&%!bb\\\\\\4%X)$%*#$%
number_format()%&7,3*'0,%*0%-')6+.=%*#$%,7<2$(%.)%X4B4%-0++.()%:'*#%.%30<<.%
)$6.(.*0(%.,-%-$3'<.+%60',*4%Y0:%-')6+.=%*#$%).<$%,7<2$(%',%_7(0)%.)%'*%:07+-%
2$%&0(<.**$-%',%?$)*$(,%_7(06$%.,-%6+.3$%*#$%_7(0%)=<20+%2$&0($%*#$%,7<2$(%
Jop[PDQK4
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7. Conditionals and Loops

7.1. Control Structures, Blocks, and Compound Statements
Figure 7.1 shows a flow chart. A flow chart is defined as a pictorial representation of how to plan the stages of a project.
It helps to visualize what decisions need to be made to accomplish a task. People control their lives by making
decisions, and so do programs. In fact, acccording to computer science books, a good language allows you to control
the flow of your program in three ways:
• Execute a sequence of statements.
• Based on a test, branch to an alternative sequence of statements.
• Repeat a sequence of statements until some condition is met.
Figure 7.1. A flow chart.


!
Well, then, PHP must be a good language.
We’ve already used programs that execute a sequence of statements, one after another. Now we examine the branching
and looping control structures that allow the flow of the program’s control to change depending on some conditional
expression.
The decision-making constructs (if, if/else, if/else if) contain a control expression that determines whether a
block of statements will be executed. The looping constructs (while, for) allow the program to repetitively execute a
statement block until some condition is satisfied.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
A compound statement or block consists of a statement or a group of statements surrounded by curly braces. The block
is syntactically equivalent to a single statement and usually follows an if, else, while, or for construct. This is a
block:
{ statement; statement; statement }
!
7.1.1. Conditionals
Conditional constructs control the flow of a program. If a condition is true, the program will execute a block of
statements and if the condition is false, flow will go to an alternate block of statements. Decision-making constructs
(if, else, switch) contain a control expression that determines whether or not a block of expressions will be
executed. If the condition after the if is met, the result is true, and the following block of statements is executed;
otherwise, the result is false and the block is not executed.
Format
if (condition){ statements; }
!
Example:
if ( $age > 21 ){ print "Let's Party!"; }

The block of statements (or single statement) is enclosed in curly braces. Normally statements are executed
sequentially. If there is only one statement after the conditional expression, the curly braces are optional.
if/else
“You better pay me now, or else . . .” Have you heard that kind of English statement before? PHP statements can be

handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if
evaluates the first conditional expression in parentheses, and if the expression evaluates to true, the block after the
opening curly braces is executed; otherwise, the block after the else is executed. The else is optional. See Example
7.1.
Format
if (condition){ statements1; } else{ statements2; }
!
Example:
if ( $x > $y ){ print "$x is larger"; } else{ print "y is larger"; }

Example 7.1.
Code!View:!
!!!(The HTML Form)
<html><head><title>Your Fare</title></head>
<body bgcolor="lightgreen">
<font face="arial" size="+1">
<form method="get" action="iffare.php">
<p>How old are you?
<input type="text" name="age" size=2>
<p>
<input type="submit" name="submit_age" value="Get Fare" >
</form>
</body>
</html>

(The PHP Script)
<html><head><title>Your Fare</title></head>
<body bgcolor="lightgreen">
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<font face="arial" size="+1">

<p>
<?php
extract($_REQUEST);
1 if ( ! isset ( $submit_age )){ // Simple conditional
exit;
}
?>
<table border="1" cellpadding="10"><tr bgcolor="yellow">
<?php
2 if ( $age >= 55 ){
3 $price = 8.25;
4 print "<td><b>You pay \$$price, the senior fare!</td>";
5 }
6 else{
7 $price = 10.00;
8 print "<td><b>You pay \$$price regular adult
fare.</td>";
}
?>
Explanation
1
If!the!variable!has!not!been!set,!the!program!will!exit.
2–
4
If!the!value!of!the!variable!$age!is!greater!than!or!equal!to!55,!lines!3!and!4!are!
executed.!See!Figures!7.2!and!7.3.
5
This!closing!curly!brace!closes!the!block!of!statements!following!the!if!expression.!
Because!there!is!only!one!statement!in!the!block,!the!curly!braces!are!not!required.
6–

8
The!else!statements,!lines!7!and!8,!are!executed!if!the!expression!in!line!2!is!false.
!


















Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 7.2. The HTML form from Example 7.1.

!
Figure 7.3. After the user presses the “Get Fare” button to submit the form. Output of the PHP script from
Example 7.1.
!

if/elseif

If you’ve got $1, we can go to the Dollar Store, else if you’ve got $10, we could get a couple of movies, else if you’ve
got $20 we could buy a CD . . . or else forget it!” PHP provides yet another form of branching, the if/elseif
construct. This construct provides a multiway decision structure.
Format
if (condition) { statements1; } elseif (condition) { statements2; }
elseif (condition) { statements3; } else{ statements4; }

If the first conditional expression following the if keyword is true, the statement or block of statements following the
expression are executed and control starts after the else block. Otherwise, if the conditional expression following the
if keyword is false, control branches to the first elseif and the expression following it is evaluated. If that
expression is true, the statement or block of statements following it are executed, and if false, the next elseif is
tested. All else ifs are tested and if none of their expressions are true, control goes to the else statement. Although
the else is not required, it normally serves as a default action if all previous conditions were false. See Example 7.2
for if/elseif construct.






Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 7.2.
Code!View:!
(The HTML Form)
<html>
<head><title>Your Movie Fare</title</head>
<body bgcolor="azure">
1 <form method="get" action="iffare2.php">
<p>How old are you?<br />
2 <input type="text" name="age" size=3 />

<p>
3 <input type="submit" name="submit_fare" value="Get Fare" />

</form>
</body>
</html>


(The PHP Script)
<html><head><title>Your Fare</title></head>
<body bgcolor="chartreuse">
<font face="arial" size="+1">

4 <?php
extract($_REQUEST); // Get form input data
5 if ( ! isset ($submit_fare) || $age == "" ){
print "You must enter your age <br />";
exit;
}
?>
<table border="1" cellpadding="10">
<tr bgcolor="azure">
<?php
6 if ($age > 0 && $age < 13) {
$price = 5.00;
print "<td><b>You pay \$$price, the child's
fare!</td>";
}
7 elseif ($age >= 13 && $age < 55 ){
$price = 8.25;

print "<td><b>You pay \$$price regular adult
fare.</td>";
}
8 elseif ( $age >= 55 && $age <= 120){
$price = 10.00;
print "<td><b>You pay \$$price, the senior fare.</td>";
}
9 else {
print "<td><b>You are not a human!</td>";
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
10 ?>
</tr>
</table>
</font>
</body>
</html>
Explanation
1
The!HTML!form!starts!here.!The!action!attribute!is!assigned!the!name!of!the!
PHP!script!that!will!be!executed!after!the!form!is!submitted.
2
The!text!box!is!named!"age"!and!will!be!sized!to!hold!three!characters.
3
The!HTML!submit!input!type!is!given!a!name,!submit_fare,!that!will!be!used!in!
the!following!PHP!script.
4
The!opening!PHP!tag!tells!PHP!to!start!processing.
5
Now!we!are!looking!at!the!PHP!instructions.!If!the!user!pressed!the!submit!

button,!this!file!will!execute.!PHP!will!store!the!names!of!the!input!devices!in!
variables,!$age!and!$submit_fare.!This!conditional!expression!tests!to!see!if!
those!variables!were!set.!If!they!weren’t!set,!then!the!form!was!either!not!
submitted!or!the!user!left!it!empty,!or!both.
6
If!is!true!that!the!user’s!age!is!greater!than!0!and!also!less!than!13,!the!block!
that!follows!the!expression!will!be!executed.!As!soon!as!the!block!is!executed,!
the!program!will!start!execution!on!line!10.!If!the!expression!evaluates!to!false,!
then!the!program!will!go!to!line!7.
7
If!the!condition!on!line!6!is!false,!the!program!checks!the!conditional!
expression!after!the!elseif,!and!if!it!is!true!(i.e.,!the!age!is!greater!than!or!
equal!to!13!and!less!than!55),!the!block!of!statements!will!be!executed.!
Otherwise,!the!program!will!go!to!line!8.
8
If!the!conditional!test!in!line!7!is!false,!this!elseif!condition!will!be!checked,!
and!if!true,!the!block!of!statements!following!it!will!be!executed.!If!false,!the!
block!of!statements!after!the!else!on!line!9!are!executed.
9
If!none!of!the!preceding!conditions!are!met,!control!goes!to!the!else!block,!
often!called!the!default!condition,!and!the!statements!in!its!block!are!executed.











Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 7.4. The HTML form from Example 7.2.

!
Figure 7.5. The PHP output from Example 7.2.
!
!
!
The switch Statement
The switch statement is an alternative to the if/elseif conditional construct, commonly called a a case statement,
and often makes the program more readable when handling multiple options.
Format
switch (expression){ case label : statement(s); break; case
label : statement(s); break; default : statement; }
!
Example:
switch ($color){ case "red": print "Hot!"; break; case "blue":
print "Cold."; break; default: print "Not a good choice.";
break; }

The value of the switch expression is matched against the expressions, called labels, following the case keyword.
The case labels are constants, either string or numeric. Each label is terminated with a colon. The default label is
optional, but its action is taken if none of the other cases match the switch expression. After a match is found, the
statements after the matched label are executed for that case. If none of the cases are matched, the control drops to the
default case. The default is optional. If a break statement is omitted, all statements below the matched label are
executed until either a break is reached or the entire switch block exits.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 7.3.

Code!View:!
(The HTML File)
<html>
<head>
<title>Pick a Font Color</title>
</head>
<body bgcolor="9BCD93">
<font face="arial" >
<b>
<form method="get" action="switch.php">
<br />Choose a font color:
<br /><input type="radio" name="color" value="red" /> red
<br
/><input type="radio" name="color" value="blue"/> blue
<br
/><input type="radio" name="color" value="purple" /> purple
<br
/><input type="radio" name="color" value="green" /> green
<p>

<input type="submit" name="submit_color" value="Submit
color" />

</form>
</b>
</body>
</html>

(The PHP Script)
<html>

<html><head><title>Font Color</title></head>
<body bgcolor="lightgreen">
<font face="arial" size="+1">
<p>
1 <?php
extract($_REQUEST);
2 if ( ! isset ($submit_color)) { // check that variables
were set
exit;
}
?>
<table border="2" cellpadding="10">
<tr bgcolor="white">
3 <?php
4 switch ( $color ) {
5 case "red":
print "<td><b><font color=".$color.">Font is red</td>";
6 break;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
7 case "blue":
print "<td><b><font color=".$color.">Font is blue</td>";
break;

case "purple":
print "<td><b><font color=".$color.">Font is
purple</td>";
break;

case "green":
print "<td><b><font color=".$color.">Font is

green</td>";
break;8 default:
print "<td><b><font color=".'black'.">Font is
black</td>";
break;
9 }
?>
</tr>
</table>
</font>
</body>
</html>! ! ! ! ! !!
Explanation
1
The!PHP!script!starts!here.
2
If!$submit_color!has!not!been!set,!then!the!form!was!not!submitted.
3
The!PHP!program!starts!here.
4
In!the!switch!expression,!the!value!of!$color!is!matched!against!the!values!of!each!of!the!
following!case!labels.!(PHP!names!the!variable,!$color,!by!the!same!name!assigned!to!the!
radio!button!and!assigns!to!the!varia b le!the!value!that!was!selected!by!the! user!when!he!or!
she!clicked!the!button.!If!the!user!clicked!red,!then!$color!will!evaluate!to!red.)!See!Figures!
7.6!and!7.7.
5
The!first!case!that!is!tested!is!"red".!If!the!user!clicked!the!“red”!radio!button,!then!the!font!
color!of!the!text!will!be!assigned!red!and!the!message!“Font!is!red”!will!be!displayed!in!the!
table!cell.
6

The!break!statement!causes!program!control!to!continue!after!line!9.!Without!it,!the!
program!would!continue!executing!statements!into!the!next!case,!"blue",!and!continue!
doing!so!until!a!break!is!reached!or!the!switch!ends,!and!we!don’t!want!that.
7
The!first!case!that!is!tested!is!"red".!If!the!user!picked!blue!as!his!or!her!choice,!then!the!
PHP!interpreter!will!skip!the!"red"!case!and!test!the!next!one,!which!is!"blue".!Because!that!
value!is!matched!successfully!against!the!value!of!the!color!variable,!the!font!is!displayed!in!
blue!and!the!message!“Font!is!blue”!will!appear!in!the!table!cell.!!
The break statement sends control of the program to line 9.
If "red" and "blue" are not matched successfully against the value of the color variable, then "purple" is
tested, and if there is a match, then its block of statements is executed.
The break statement sends control of the program to line 9.
If "red", "blue", or "purple" are not matched successfully against the value of the color variable, then
"green" is tested, and if there is a match, its block of statements is executed.
The!break!statement!sends!control!of!the!program!to!line!9.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
blue!and!the!message!“Font!is!blue”!will!appear!in!the!table!cell.!!
The break statement sends control of the program to line 9.
If "red" and "blue" are not matched successfully against the value of the color variable, then "purple" is
tested, and if there is a match, then its block of statements is executed.
The break statement sends control of the program to line 9.
If "red", "blue", or "purple" are not matched successfully against the value of the color variable, then
"green" is tested, and if there is a match, its block of statements is executed.
The!break!statement!sends!control!of!the!program!to!line!9.
8
The!default!statement!block!is!executed!if!none!of!the!preceding!cases!is!matched.!This!
final!default!statement!is!not!necessary,!but!is!good!practice!in!case!you!should!decide!to!
replace!the!default!with!an!additional!case!label!later!on.
9
The!final!curly!brace!ends!the!switch!statement!block.

!
Figure 7.6. The HTML form from Example 7.3.

!











Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 7.7. The user selected the button labeled “red”. The PHP output from Example 7.3.

7.2. Loops
Loops are used to execute a segment of code repeatedly until some condition is met. Suppose you have a program that
prints 10, 9, 8, . . . down to 1 and then prints “Blast off!”. To get from 10 to 1, you could write 10 print statements or
you could write one if you use a loop.
PHP’s basic looping constructs are the following:
• while
• for
• foreach
• do/while
Loops work differently than if statements. A block of statements after an if are executed once, whereas a block of
statements after a loop expression can be executed repeatedly.
7.2.1. The while Loop

The while statement keeps executing its statement block as long as the expression after the while evaluates to true;
that is, nonnull, nonzero, nonfalse. If the while expression evaluates to true, the block of statements that follow are
executed. After the last statement in the block is executed, the program jumps back to the while expression again and
checks if the expression is still true. If the condition never changes and is true, the loop will iterate forever (infinite
loop). The programmer determines how many times he or she wants the loop to iterate by changing the test condition or
by breaking out of the loop with a break statement. If the condition is false, control goes to the statement right after
the closing curly brace of the loop’s statement block.
The break and continue functions are used for loop control.
Example 7.4 demonstrates how a while loop works. The output is shown in Figure 7.8.
Format
while (condition) { statements; increment/decrement counter; }


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 7.4.

!
Explanation
1
The!PHP!program!starts!here.
2
The!variable!$i!is!initialized!to!10.
3
The!expression!after!the!while!is!tested.!If!$i!is!greater!than!0,!the!block!in!
curly!braces!is!entered!and!its!statements!are!executed.!If!the!expression!
evaluates!to!false!(i.e.,!$i!is!not!greater!than!0),!the!loop!block!exits!and!
control!goes!to!line!8.
4
The!value!of!$i!is!displayed!in!the!browser!window.
5

The!value!of!$i!is!decremented!by!1.!This!step!is!crucial!because!if!the!value!of!
$i!never!changes,!the!loop!will!never!end.
6
This!curly!brace!marks!the!end!of!the!while!loop’s!block!of!statements.!
Program!control!will!follow!the!arrow!in!the!example,!as!long!as!the!while!
expression!tests!true.
7
The!PHP!program!ends!here.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
8
This!HTML!text!is!displayed!after!the!loop!exits.


Figure 7.8. The while loop. Output from Example 7.4.
!
!
7.2.2. The do/while Loop
The do/while statement executes a block of statements repeatedly until a condition becomes false. Due to its
structure, this loop necessarily executes the statements in the body of the loop at least once before testing its expression,
which is found at the bottom of the block. Example 7.5 demonstrates how the do/while loop works. The output is
shown in Figure 7.9.
Format
do { statements;} while (condition);

Example 7.5.
<html>
<head>
<title>Looping Constructs</title>
<body bgcolor='f0f8ff'>
<h3>Do While Loop</h3>

<font face='arial' size='+1'>
<?php
1 $i=10;
2 do{
3 echo "$i ";
4 $i ;
5 }while ( $i > 0 );
?>
</body>
</html>



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×