Title: PHP: Further Skills
1PHP Further Skills
2Topics covered
- Brief re-cap of core PHP characteristics
- Arrays
- Loops
- Code organisation
- Error handling
- Online resources
3Brief Overview of Core PHP
- Variables
- sign, weakly typed
- Constants
- Conditional branching
- If statement
- Switch statement
- Logical comparison
- Interacting with browser
- _POST
- _GET
- HTML ltformgt elements
4Arrays - Simple collections
- It is common to group related data
- Ordered set of related elements
- Arrays in PHP are very simple
- Weakly typed just like variables
- Accessed using brackets
- You encountered an array when posting a form
- _POST is an array provided by PHP to present
form data - Access array elements using a key
- Either numerical or text based key
- _POSTtxtMsg
- soldiers0
5Arrays - declare and use
- Defining an array is similar to a variable
- Same rules apply to array variable names
- Can be declared empty or initialised
- For example
- myarray array()
- myarray0 Trevor Adams
- echo myarray0
- Prints Trevor Adams
- Or
- myarray (0 gt Trevor Adams)
- echo myarray0
- Prints Trevor Adams
6Arrays - Characteristics
- Arrays can store any type of variable, including
other arrays. E.g. - myarray array()
- myarray0 array()
- myarray00 Trevor Adams
- echo myarray00
- Prints Trevor Adams
- There is no size limit
- Is limited by server capacity
- Be nice to your server
7Arrays - working with data
- Arrays are collections of related data
- Sometimes necessary to process this data
- Need a way of iterating through an array
- Arrays need repetitive operations
- This means Loops!
- With out further a do
- we shall come back to arrays soon
8Loops - iteration made easy
- Many tasks involve iteration
- The repetition of a process
- Computer programs do the job well
- PHP provides us with choices
- While
- Do
- For
- foreach
- Each of them are useful in different ways
9Loops - While
- While loops are the most simple loop type
- Similar in syntax to an IF statement
- Code runs while the test expression is true
- E.g.
- While(valid true)
- //execute commands
- //test the test expression
-
- BE SURE to make sure your code can exit the loop
- At some point, valid must not equal true to break
the loop - Avoid infinite loops, they ruin everyone's day
10Loops - Do
- Do loop is extremely similar to a while loop
- Major difference, text expression is at the end
- This loop will always execute at least once
- E.g.
- Do
- //execute these statements at least once
- //another statement
- while(something true)
- Again, make sure your loop can end!
11Loops - for
- For loops are best when the number of iterations
are known - Using pseudo code
- for(set loop counter test loop counter adjust
loop counter) - // execute statements within braces
-
- Trivial example would be to print out a
multiplication table (up to 12)
12Loops - for
- mulitple 5
- for(counter 1 counterlt13 counter)
- answer multiple counter
- echo counter multiple . answer .ltbr
/gt -
- This code would result in output
- 1 5 5
- 2 5 10
- 3 5 15 .. And so on
- Ensure you do not erroneously adjust counter
during the loop
13Loops - foreach
- We get back to arrays!
- The foreach loop is an extension of the for loop
- Except you do not need to know the number of
elements - It can move through an array for you
- Extremely useful loop for traversing arrays
14Loops - foreach
- The foreach loop is available in two formats
- Assume the following array
- campussot Stoke-on-Trent
- campussta Stafford
- campuslic Lichfield
- A foreach loop can be used to iterate the entire
array
15Loops - foreach in use
- First method allows us to get the values. E.g.
- foreach(campus as campusname)
- echo campusname . ltbr /gt
-
- Would output
- Stoke-on-Trent
- Stafford
- Lichfield
16Loops - foreach in use
- The second method allows access to the key
- foreach(campus as key gt name)
- echo key - nameltbr /gt
-
- Would produce output
- sot - Stoke-on-Trent
- sta - Stafford
- lic - Lichfield
- This loop is excellent at traversing arrays of
elements of unknown quantity
17Arrays and Loops - overview
- Arrays - collections of related data
- Act like variables
- Access sub-elements using square brackets
- Can index elements with numerical or textual keys
- Loops - useful for repetitive processing
- while and do test a Boolean expression
(something true) - for loops require a counter
- foreach loops traverse arrays
18Code Organisation
- All about being efficient and productive
- Skills you should possess as a programmer
- Creating functions
- Calling functions
- Scope
- Modular code
- Placing code in separate files
- Make commonly used code available
19Functions - defining and using
- We create functions for a number of reasons
- Avoid repetition (E.g. frequently used
calculations) - Easier to test small code fragments
- Functions have a name, and optionally may take
arguments - Functions may merely execute commands
- They might return a value
- Completely up to the programmer
20Functions - defining and using
- You can declare a function anywhere inside PHP
code blocks - A function is declared using the keyword
function. E.g. - function sum_numbers (a, b)
- return a b
-
- This function could then be used in PHP code.
E.g. - num1 4
- num2 6
- myAnswer sum_numbers(num1, num2)
- echo myAnswer // would show 10
21Functions - defining and using
- function sum_numbers (a, b)
- return a b
-
- a and b in this function are arguments
- They exist inside the function braces only
- It is said they have local scope
- Values you pass to a function are not affected
outside of it
22Functions - defining and using
- A function does not have to return a value
- Possible to use output text
- E.g. creating a HTML header and footer function
- function print_header(title)
- echo lthtmlgtltheadgtlttitlegttitlelt/titlegtlt/headgt
- echo ltbodygt
-
- Function print_footer()
- echo lt/bodygtlt/htmlgt
23Functions - defining and using
- lt?php
- print_header(Sample page)
- echo ltpgtHello World!lt/pgt
- print_footer()
- ?gt
- Would produce
- lthtmlgtltheadgtlttitlegtSample pagelt/titlegtlt/headgtltbody
gt - ltpgtHello World!lt/pgt
- lt/bodygtlt/htmlgt
24Code - Include / Require
- PHP files do not have to be web pages
- It is possible to have a PHP made completely of
functions - If this page was to be called in a browser, it
would be completely blank - Including other files within a PHP script is a
common form of modularisation - Common with many server side scripting languages
- Allows the programmer to place code required in
many places into one location, available to all
scripts.
25Code - Include / Require
- PHP uses the include function and the require
function to incorporate other files - Place our print_header and print_footer in a file
called utils.php - We create index.php - we can then use
- lt?php
- include(utils.php)
- print_header(My Homepage)
- echo lth1gtHello World!lt/h1gt
- print_footer() ?gt
- Require can be used instead of include
- Require causes a page error however, if the file
to include cannot be found
26Code Organisation - Overview
- Functions allow you to separate your frequently
used code - Promotes good practice
- Code re-use
- Less typing!
- Include files allow a programmer to create useful
libraries of code - Promotes further good practice
- Allows you to create global code
27Error Handling with PHP
- We should now have enough basic programming
knowledge to consider errors - Error handling is perhaps one of the main weak
points of PHP - We shall be covering
- Why we care
- Notices
- Syntax errors
- Program errors
- Logical errors
- How to handle and avoid errors
28Why do we care about errors?
- Security - paramount to any web application
- Data comes from non-trusted sources (users!)
- Web messages
- Standard programs have the ability to pipe error
messages in many ways (log, dialog etc.) - PHP only has the option of outputting messages to
the browser - It does so, you might have already seen messages
in your own code - Nothing says amateur like rogue error messages in
a production application
29PHP Errors - Notices
- A notice is not actually an error at all
- It merely serves as information to the programmer
- lt?php
- echo "lth1gtmessagelt/h1gt"
- ?gt
- Produces
30PHP Errors - Notices
- You know that _at_ suppresses the message
- A better technique is to test the variable first
- Use the isset() function or the empty() function
- isset(varname) returns true if the variable has
been given a value - empty(varname) returns true if it is null
- lt?php
- If(isset(message))
- echo lth1gtmessagelt/h1gt
- ?gt
- Testing the variable for a value removes the
warning message from the script
31PHP Errors - Syntax Errors
- Syntax errors are easy to spot.
- Usually caused by inputting code incorrectly
- eco lth1gtmessagelt/h1gt
- Use the line number to find the error and correct
it
32PHP Errors - Program Errors
- These errors occur when a error happens that is
generally unforeseen - Trying to include a file which does not exist
- Trying to connect to a database that is offline
- Results of functions should generally be checked
and handled well - Solutions to these issues are often complex
- We shall return to these errors later in the
module
33PHP Errors - Logical Errors
- Hardest type to spot!
- Typical example is a program script attempting to
divide by zero - This could happen in a for loop for example
- Read the errors on screen
- Line numbers are useful
- Messages are meaningful
- Take the time to think about the message
34PHP Errors Top causes
- Typing mistake - check your spelling first
- Construct improperly closed
- E.g. missing a brace
- Use comments to help
- Missing a semi-colon after a statement
- Getting the name of a function wrong
- E.g. eco Hello
- Not closing a string
- E.g. echo Hello
35PHP Error Handling - overview
- Topics covered
- Why we bother with error handling
- Types of errors
- Notices
- Syntax
- Program errors
- Logical errors
- How to handle errors
- Checking with isset() and empty()
36Topics covered this lecture
- Arrays
- A type of variable, containing related items
- Accessed via keys, numerical or textual
- Values accessed using square brackets
- Code Organisation
- Why we use functions
- The ability to include external files
- PHP Error Handling
- Why we bother with errors
- Different types of errors
- Top causes of errors
37Online resources
- PHP web site - http//www.php.net/
- Contains a searchable database of PHP functions
- Try searching for sort in the function list
- You will be presented with an impressive list of
PHP functions involving sorting arrays - Learn to use the PHP manual - it is an invaluable
resource for programming PHP.