Title: Powering Scripts with Functions
1Powering Scripts with Functions
- David Lash
- Chapter 4
- Using and writing your own functions
2Objectives
- Introduce this notion of a function
- Some basic numeric PHP functionsE.g., sqrt(),
round(), is_numeric(), and rand(). - The print() function
- The date() function.
- See what we can do for ourselves
3Using Some Basic PHP Functions
- PHP has a bunch of built-in functions.
- They do things automatically for you
- For example,
- print (Hello World)
- We will look at other functions that do things
for you
Creates output with its one argument (or input
variable).
Name of function
4The sqrt() Function Just to warm-up
- sqrt() - input a single numerical argument and
returns its square root. - For example, the following
- xsqrt(25)
- ysqrt(24)
- print "xx yy"
- Will output
- x5 y4.898979485566
- y144
- num sqrt(y)
Function name
Argument or parameter to function
Returned value
5The round() Function
- round() - rounds number to nearest integer
- For example, the following
- xround(-5.456)
- yround(3.7342)
- print "xx yy"
- Will output x-5 y4
6True/false Return values
- So far functions have either returned nothing
(e.g., print() ) or a number (e.g., round() ) - Functions can also return a true or false value.
- True is sometimes thought of 1 and false of 0
- These are called boolean returned
- Why would you do this? .
- Makes testing something easy
- if ( got_a_number() ) do stuff
-
- Lets look at a true/false function .
This is just an example it is not a valid
statement
7The is_numeric() Function
- is_numeric() determines if a variable is a valid
number or a numeric string. - It returns true or false.
- Consider the following example...
- if (is_numeric(input))
- print "Got Valid Numberinput"
- else
- print "Not Valid Numberinput"
-
- If input was 6 then would Got Valid Number6
- If input was Happy then would output Not
Valid NumberHappy
Could use to test if input was string or numeric
8Remember this Consider average example
- lthtmlgt
- ltheadgt
- lttitlegtSurvey Formlt/titlegt
- lt/headgt
- ltbodygt
- lth1gtClass Surveylt/h1gt
- ltFORM METHOD"POST" ACTION"newaverage.php"gt
- ltbrgtPick A Number ltBRgt ltinput typetext
namenum1gt - ltbrgtPick A Number 2 ltBRgtltinput typetext
namenum2gt - ltbrgtPick A Number 3 ltBRgtltinput typetext
namenum3gt - ltbrgtltinput type"submit" value"Submit"gt
- ltinput type"reset" value"Erase"gt
- lt/formgt
- lt/BODYgt
- lt/HTMLgt
9PHP Code
- lthtmlgt ltheadgt lttitlegt Guess the Dice lt/titlegt
- ltbodygt
- ltFont size5 colorblackgt Your Averages
Arelt/fontgt - ltform action"guessdice2.php" methodpostgt
- lt?php
- num1 _POSTnum1
- num2 _POSTnum2
- num3 _POSTnum3
- if ( !is_numeric(_POSTnum1)
!is_numeric(_POSTnum2) !is_numeric(_POSTn
um3) ) - print "Error please fill in numericaly
values for all three inputs" - print "num1num1 num2num2 num3num3"
- exit
-
- aver (num1 num2 num3 ) / 3
- print "ltfont size4 colorbluegt"
- print "num1 num1 "
http//condor.depaul.edu/dlash/extra/Webpage/exam
ples/newaverage.html
10The rand() Function can be fun
- Use rand() to generate a random number.
- You can use random numbers to simulate a dice
roll or a coin toss or to randomly select an
advertisement banner to display. - rand() gen a number from 1 to max number.
- E.g.,
- num rand()
- print numnum
- Might output
- num 12
11The rand() Function - Part II
- Use the rand() to generate a number 1-6
- numb rand()
- rnumb (numb 6) 1
- print "Your random dice toss is rnumb"
- The random number generated in this case can be a
1, 2, 3, 4, 5, or 6.
Think a second Asks for remainder of numb /
6 which is always 0,1,2,3,4, or 5 so you add 1 to
force it to be 1,2,3,4,5, or 6
12 A Full Example ...
- Consider the following application
- Uses an HTML form to ask the end-user to guess
the results of dice roll - ltinput type"radio" nameguess" value1"gt 1
- ltinput type"radio" nameguess" value2"gt 2
- ltinput type"radio" nameguess" value3"gt 3
- ltinput type"radio" nameguess" value4"gt 4
- ltinput type"radio" nameguess" value5"gt 5
- ltinput type"radio" nameguess" value5"gt 6
- http//condor.depaul.edu/dlash/extra/Webpage/exam
ples/guessdice.php
13Consider the following ...
- ltheadgt lttitlegt Guess the Dice lt/titlegt
- ltbodygt
- lt?php
- guess _POST"guess"
- if ( guess gt 1 guess lt6 )
- numb rand() 6 1
- print "numbnumb ltbrgt"
- dice"dicenumb.gif"
- print "The Random Dice Generated Is
..." - print "ltimg srcdicegt"
- print " ltbrgt Your Dicedice ltbrgt"
- if ( guess numb )
- print "ltbrgtltfont size4
colorbluegt You got it right " - print "ltbrgt ltfont size4
colorbluegt Your Guess is guess " - else
- print "ltbrgt ltfont size4
colorredgt You got it WRONG ? " - print "ltbrgtltfont size4
colorredgt Your Guess is guess " -
- else
Generate random number 1-6
Set which image to display
Display either dice1.gif, dice2,gif,
dice3.gif, dice4.gif, dice5.gif, or dice6.gif
Check to see if got it right or wrong
14Objectives
- To learn to use several PHP functions useful for
Web application development - Some basic numeric PHP functionsE.g., sqrt(),
round(), is_numeric(), and rand(). - The print() function
- The date() function.
- To learn to write and use your own functions
15More information on the print() Function
- You dont need to use parenthesis with print()
- Double quotes means output the value of any
variable - x 10
- print ("Mom, please send x dollars")
- Single quotes means output the actual variable
name - x 10
- print ('Mom, please send x dollars')
- To output a single variables value or
expression, omit the quotation marks. - x5
- print x3
Double quotes
Single quotes
16Generating HTMLTags with print()
- Using single or double quotation statements can
be useful when generating HTML tags - print 'ltfont color"blue"gt'
- This above is easier to understand and actually
runs slightly faster than using all double
quotation marks and the backslash (\) character - print "ltfont color\"blue\"gt"
using \ allows to be output
17Objectives
- To learn to use several PHP functions useful for
Web application development - Some basic numeric PHP functionsE.g., sqrt(),
round(), is_numeric(), and rand(). - The print() function
- The date() function.
- To learn to write and use your own functions
18The date() Function
- The date() function is a useful function for
determining the current date and time - The format string defines the format of the
date() functions output - day date('d')
- print "dayday"
- If executed on December 27, 2001, then it would
output day27.
Request date() to return the numerical day of the
month.
19Selected character formats for date()
20More About date()
- You can combine multiple character formats return
more than one format from the date() - For example,
- today date( 'l, F d, Y')
- print "Todaytoday"
- On MQY 11, 2004, would output
- TodayTuesday, May 11, 2004.
21 A Full Example ...
- Consider the following Web application that uses
date() to determine the current date and the
number of days remaining in a stores sale event. - Sale runs from 12/1 until 1/10/02
22Receiving Code
- 1. lthtmlgt ltheadgtlttitlegt Our Shop lt/titlegt lt/headgt
- 2. ltbodygt ltfont size4 color"blue"gt
- 3. lt?php
- 4. today date( 'l, F d, Y')
- 5. print "Welcome on today to our huge blowout
sale! lt/fontgt" - 6. month date('m')
- 7. year date('Y')
- 8. dayofyear date('z')
- 9. if (month 12 year 2001)
- 10. daysleft (365 - dayofyear 10)
- 11. print "ltbrgt There are daysleft sales days
left" - 12. elseif (month 01 year 2002)
- 13. if (dayofyear lt 10)
- 14. daysleft (10 - dayofyear)
- 15. print "ltbrgt There are daysleft sales
days left" - 16. else
- 19. print "ltbrgtSorry, our sale is over."
- 20.
- 21. else
Get a date in format day of week, month, day and
year
Get month number 1-12, , 4 digit year and day
of year
Check if its Dec 2001. Then figure out days left
in year and add 10.
If if 1/2002 already, how many days left before
1/10?
Otherwise sale is ove.
23 The Output ...
- The previous code can be executed at
http//webwizard.aw.com/phppgm/C3/date.php
24Create your own functions ...
- Write your own function to
- group a set of statements, set them aside, and
turn them into mini-scripts within a larger
script. - The advantages are
- Scripts that are easier to understand and change.
- Reusable script sections.
- Smaller program size
25Writing Your Own Functions
- Use the following general format
- function function_name()
- set of statements
-
Include parentheses at the end of the function
name
Use the keyword function here
The function runs these statements when called
Enclose in curly brackets.
26For example
- Consider the following
- function OutputTableRow()
- print 'lttrgtlttdgtOnelt/tdgtlttdgtTwolt/tdgtlt/trgt'
-
- You can run the function by including
- OutputTableRow()
27As a full example
- 1. lthtmlgt
- 2. ltheadgtlttitlegt Simple Table Function lt/titlegt
lt/headgt ltbodygt - 3. ltfont color"blue" size"4"gt Here Is a Simple
Table lttable border1gt - 4. lt?php
- 5. function OutputTableRow()
- 6. print 'lttrgtlttdgtOnelt/tdgtlttdgtTwolt/tdgtlt/tr
gt' - 7.
- 8. OutputTableRow()
- 9. OutputTableRow()
- 10. OutputTableRow()
- 11. ?gt
- 12. lt/tablegtlt/bodygtlt/htmlgt
OutputTableRow() function definition.
Three consecutive calls to the OutputTableRow()
function
28Would have the following output
29TIP Use Comments at the Start of a Function
- It is good practice to place comments at the
start of a function - For example,
- function OutputTableRow()
- // Simple function that outputs 2 table cells
- print 'lttrgtlttdgtOnelt/tdgtlttdgtTwolt/tdgtlt/trgt'
-
30Passing Arguments to Functions
- Input variables to functions are called arguments
to the function - For example, the following sends 2 arguments
- OutputTableRow("A First Cell", "A Second Cell")
- Within function definition can access values
- function OutputTableRow(col1, col2)
- print "lttrgtlttdgtcol1lt/tdgtlttdgtcol2lt/tdgtlt/trgt"
-
31Consider the following code
- 1. lthtmlgt
- 2. ltheadgtlttitlegt Simple Table Function lt/titlegt
lt/headgt ltbodygt - 3. ltfont color"blue" size4gt Revised Simple
Table lttable border1gt - 4. lt?php
- 5. function OutputTableRow( col1, col2 )
- 6. print "lttrgtlttdgtcol1lt/tdgtlttdgtcol2lt/tdgtlt
/trgt" - 7.
- OutputTableRow( Row 1 Col 1 , Row 1 Col 2 )
- OutputTableRow( Row 2 Col 1 , Row 2 Col 2 )
- OutputTableRow( Row 3 Col 1 , Row 3 Col 2 )
- OutputTableRow( Row 4 Col 1 , Row 4 Col 2 )
- 12. ?gt
- 13. lt/tablegtlt/bodygtlt/htmlgt
OutputTableRow() Function definition.
Four calls to OuputTableRow()
32Returning Values
- Your functions can return data to the calling
script. - For example, your functions can return the
results of a computation. - You can use the PHP return statement to return a
value to the calling script statement - return result
- This variables value will be returned to the
calling script.
33Example function
- 1. function Simple_calc( num1, num2 )
- 2. // PURPOSE returns largest of 2 numbers
- 3. // ARGUMENTS num1 -- 1st number, num2 --
2nd number - 4. if (num1 gt num2)
- 5. return(num1)
- 6. else
- 7. return(num2)
- 8.
- 9.
- What is output if called as follows
- largest Simple_calc(15, -22)
Return num1 when it is the larger value.
Return num2 when it is the larger value.
34Consider an application that
Main form element Starting Value ltinput
type"text" size"15 maxlength"20"
name"start"gt Ending Value ltinput type"text"
size"15 maxlength"20" name"end"gt
35A Full Example ...
- Consider a script that calculates the percentage
change from starting to an ending value - Uses the following front-end form
- Starting Value ltinput type"text" size"15
- maxlength"20" name"start"gt
- Ending Value ltinput type"text" size"15
- maxlength"20" name"end"gt
http//webwizard.awl.com/phppgm/C4/driveperc.html
36The Source Code
- 1. lthtmlgt
- 2. ltheadgtlttitlegt Your Percentage Calculation
lt/titlegtlt/headgtltbodygt - 3. ltfont color"blue" size4gt Percentage
Calculator lt/fontgt - 4. lt?php
- 5. function Calc_perc(buy, sell)
- 6. per ((sell - buy) / buy) 100
- 7. return(per)
- 8.
- 9. start _POSTstart end
_POSTend - 10. print "ltbrgtYour starting value was start."
- 11. print "ltbrgtYour ending value was end."
- 12. if (is_numeric(start) is_numeric(end) )
- 13. if (start ! 0)
- 14. per Calc_perc(start, end)
- 15. print "ltbrgt Your percentage change
was per ." - 16. else print "ltbrgt Error! Starting
values cannot be zero " - 17. else
- 18. print "ltbrgt Error! You must have valid
numbers for start and end " - 19.
Calculate the percentage change from the
starting value to the ending value.
The call to Calc_perc() returns the
percentage change into per.
37Using External Script Files
- Sometime you will want to use scripts from
external files. - Reuse code from 1 situation to another
- Create header and footer sections for code
- PHP supports 2 related functions
- require ("header.php")
- include ("trailer.php")
- Both search for the file named within the double
quotation marks and insert its PHP, HTML, or
JavaScript code into the current file.
The require() function produces a fatal error if
it cant insert the specified file.
The include() function produces a warning if it
cant insert the specified file.
38Consider the following example
The script will output these lines when the file
is included.
- 1. ltfont size4 color"blue"gt
- 2. Welcome to Harrys Hardware Heaven!
- 3. lt/fontgtltbrgt We sell it all for you!ltbrgt
- 4. lt?php
- 5. time date('Hi')
- 6. function Calc_perc(buy, sell)
- 7. per ((sell - buy ) / buy) 100
- 8. return(per)
- 9.
- 10. ?gt
The value of time will be set when the file is
included.
This function will be available for use when the
file is included.
39header.php
- If the previous script is placed into a file
called header.php - 1. lthtmlgtltheadgtlttitlegt Hardware Heaven
lt/titlegtlt/headgt ltbodygt - 2. lt?php
- 3. include("header.php")
- 4. buy 2.50
- 5. sell 10.00
- 6. print "ltbrgtIt is time."
- 7. print "We have hammers on special for
\sell!" - 8. markup Calc_perc(buy, sell)
- 9. print "ltbrgtOur markup is only markup!!"
- 10. ?gt
- 11. lt/bodygtlt/htmlgt
Include the file header.php
Calc_perc() is defined in header.php
40Would output the following ...
41More Typical Use of External Code Files
- More typically might use one or more files with
only functions and other files that contain HTML - For example, might use the following as
footer.php. - lthrgt
- Hardware Harry's is located in beautiful downtown
Hardwareville. - ltbrgtWe are open every day from 9 A.M. to
midnight, 365 days a year. - ltbrgtCall 476-123-4325. Just ask for Harry.
- lt/bodygtlt/htmlgt
- Can include using
- lt?php include("footer.php") ?gt
42Even More Practical Example
- Check out the following link http//condor.depaul.
edu/dlash/website/Indellible_Technologies.php - Original found at perl-pgm.com
- Could hard code header in each file that needs it
or - Separate the header info into a different file
(Say header.php.) - Include it everywhere needed.
- E.g., ltinclude header.phpgt
- lthtmlgt
- ltheadgt
- lttitlegtIndellible Technologieslt/titlegt
-
- lt/headgt
- ltbody text"000000" bgcolor"ffffff"
link"000099" vlink"990099" - alink"000099"gt
- lt?php include "header.php" ?gt
43Here is contents of header.php
- lttable cellpadding"0" cellspacing"0" border"0"
width"100"gt - lttbodygt
- lttrgt
- lttd valign"top"gt ltimg
src"INdelliblecolor3.gif" alt"" width"792" - height"102"gt
- ltbrgt
- lt/tdgt
- lt/trgt
- lt/tbodygt
- lt/tablegt
- lttable cellpadding"0" cellspacing"0" border"0"
width"792"gt - lttbodygt
- lttrgt
- lttd valign"bottom"
bgcolor"33ffff" align"center"gtlta - href"requestinfo.html"gt
Request Informationlt/agt lta - href"preregister.html"gt
Pre-registerlt/agt - lta href"schedule.html
"gtCourseCataloglt/agt - nbsplta
href"comments.html"gtTestimonialslt/agtltbrgt - lt/tdgt
44Summary
- To learn to use several PHP functions useful for
Web application development - Some basic numeric PHP functionsE.g., abs(),
sqrt(), round(), is_numeric(), and rand(). - The print() function
- The date() function.
- To learn to write and use your own functions
- Writing own functions
- returning values
- Passing arguments
45Here is the receiving code ...
- ltlthtmlgt ltheadgt lttitlegt Receiving Script lt/titlegt
ltbodygt - lt?php
- passwd _POST"pass"
- fname _POST"fname"
- if (passwd "password" )
- print "Thank you fname welcome
ltbrgt" - print "Here is my site's
content" - else
- print "Hit the road jack you
entered passwordpasswdltbrgt" - print "Contact someone to get the
passwd" -
- ?gt
- lt/bodygt lt/htmlgt
46Summary
- Looked at using conditional statements
- if statement
- elsif statement
- else statement
- conditional statements have different format
- if ( x lt 100 )
- x y 1
- z y 2
-
- Can do multiple tests at once
- if ( x lt 100 name george )
- x y 1
- z y 2
-
- Can test if variable(s) set from form
- if ( !_POSTvar1 !_POSTvar1 )