Date post: | 03-Jan-2016 |
Category: |
Documents |
Upload: | augusta-arabella-norris |
View: | 226 times |
Download: | 0 times |
Arrays• There are three different kind of arrays:• Numeric array - An array with a numeric ID key • Associative array - An array where each ID key is
associated with a value • Multidimensional array - An array containing one or
more arrays
2
Creating Numeric Arrays• An array is a list variable. It contains multiple elements indexed by numbers or strings
• It enables you to store, order and access many values under one name
• The array() is useful when you want to assign multiple values to an array at one time e.g.
• In this example the ID key is automatically assigned:
$users=array(“Bert”, “Harry”, “Betty”);
3
Continued..• Access the second element in the array:
print “$users[1]”;• Alternatively, you can create a new array using the array
identifier:
$users[]=“Bert”;
$users[]=“Harry”;
$users[]=“Betty”;
4
Adding a new element• Use the array identifier to add new elements to the array:
$users=array(“Bert”, “Harry”, “Betty”);
$users[]=“Sally”;
5
Associative Arrays• An array that utilises keys (names) to access values rather than index numbers, making it more friendly to use
• Creates an associative array called $ages with three elements:
<?php
$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
6
Example$greetings = array("Irish"=>"Dia Duit", "French"=>"Bonjour",
"German"=>"Guten Tag");
print "Hello ". $greetings['French'];
Output: Hello Bonjour
7
Example<?php
$character=array ("name"=>"bob", "occupation"=>"superhero", "age"=>30,"special power"=>"x-ray vision");
echo $character["age"];
echo "<br/>";
$character["name"]="bob";$character["occupation"]="superhero";$character["age"]=30;$character["special power"]= "x-ray vision";
echo $character["occupation"];?>
8
Multidimensional Arrays• An element in an array could be a value, an object or
another array
• A multidimensional array is an array of arrays i.e. an array that stores an array in each of its elements:
E.g.
$array[1][2];
9
Example
name title salary
employee 1
Dana Owner $60,000
employee 2
Matt Manager $40,000
employee 3
Susan Clerk $30,000
10
<?php$employees["employee 1"]["name"] = "Dana";$employees["employee 1"]["title"] = "Owner";$employees["employee 1"]["salary"] = "$60,000";
$employees["employee 2"]["name"] = "Matt";$employees["employee 2"]["title"] = "Manager";$employees["employee 2"]["salary"] = "$40,000";
$employees["employee 3"]["name"] = "Susan";$employees["employee 3"]["title"] = "Cashier";$employees["employee 3"]["salary"] = "$30,000";
echo $employees["employee 2"]["name"]." is the ".$employees["employee 2"]["title"]." and he earns ".$employees["employee 2"]["salary"]." a year.";
?>
11
Accessing Arrays• array_merge();• array_push();• array_shift();• array_slice();• sort();• asort();• ssort();
12
PHP Functions• Foreach - prints the combined array with a break between
each element
• count — Count all elements in an array, or properties in an object
• print_r() displays information about a variable in a way that's readable by humans
13
Array_merge() - Accepts two or more arrays and returns a
merged array combining all of the elements
<?php$first=array("a", "b", "c");$second=array(1,2,3);$third=array_merge($first, $second);
foreach($third as $val){print "$val<br>";}?>
14
Array_push() - Accepts an array and any number of further parameters
each of which is added to the array. Returns the total number of elements in the array
<?php$first=array("a", "b", "c");$total=array_push($first, 1, 2, 3);print "There are $total elements in \$first<p>";
foreach($first as $val){print "$val<br>";}?>
15
Note • The $first array contains original elements plus three
integers we passed to it• Notice we use \$first – we wish to print it as a string not a
variable• To print $ we must use \• Known as escaping a character
16
Array_shift() Removes and returns the first element of the array
passed to it<?php
$an_array=array("a", "b", "c");
while (count($an_array))
{
$val=array_shift($an_array);
print "$val<br>";
print "there are". count($an_array). "elements in \$an_array<br>";
}
?>
17
Array_slice() - Allows you to extract a chunk of an array. It accepts an
array as an argument, a starting position, and a length(optional)
<?php$first=array("a", "b", "c", "d", "e", "f");$second=array_slice($first, 2, 3);
foreach($second as $var){print "$var<br>";}?>
18
More on Arrays - Sort()
• Accepts an array as an argument and sorts it either alphabetically if any strings are present or numerically if all elements are numbers
• This function assigns new keys for the elements in the array
• Existing keys will be removed
20
Example<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");
sort($my_array);
print_r($my_array);
?>
21
Asort() Accepts an associative array and sorts its values preserving the
keys
<?php
$my_array = array("b" => "Rabbit", "c" => "Dog", "a" => "Cat");
asort($my_array);
print_r($my_array);
?>
22
Ksort() - Sorts an associative array by keys
<?php
$my_array = array("b" => "Ruler", "c" => "Sharpener", "a" => "Book");
ksort($my_array);
print_r($my_array);
?>
23
Questions?• What is the index number of the last element of the array
defined below? $users=array(“Harry”,”Bob”, “Sandy”);
• What would be the easiest way to add “Susan” to the array defined above?
24
Answer<?php$users=array("Harry","Bob", "Sandy");
foreach ($users as $item){
print ("$item<br>");}
$users[]="Sally";
foreach ($users as $item){
print ("$item<br>");}?>
25
Lifecycle of an PHP Web Application
1. Requirements Analysis
2. Specification of Requirements
6. Analysis of Statistics and Maintenance
3. Design
4. Programming
5. Marketing
Step 1. Website Requirements and Analysis• Who is your targeted audience?• Knowing who they are will help you understand what they
need, in terms of what kind of functionality should your website provide them with, that they will require? Will they need product reviews? Will they be searching for the lowest prices? Etc.
• Based on this you can write all the functionalities of your website, all the requirements your website must fulfil
• These requirements and the analysis of your target user will help you with the next steps
Step 2 Specification of Requirements • Revisit requirements in step 1 and for each you will develop a use-
case
• A use-case is where you will determine 'what will the user do/ what action will the user take'. Here's an example of a use case:User Begins at Home Page --> User clicks on Featured Item Image --> User sees item description --> User goes to merchant site via Link
• use-case scenarios - if the user doesn't find what they're looking for, perhaps we can offer an 'alternative' which is related to what they're looking for
• Other requirements you need to consider are your own requirements of the website - what happens when the website grows and you no longer need only 5 merchants, you now need 50
• Once you have identified what you will need and what the user will need, you're ready plan the website structure and design
Step 3 - Design• What PHP pages will be needed?
• What Database tables and columns will be need to be created?
• What information will the PHP pages need from the database?
Design• When you have decided upon any of the above project needs it is important that you document these decisions so that they are effectively communicated to other development team members
• It is important that you dedicate enough time to your design phase
• Defects created in the design phase will cause delays in later stages of the project life.
Design• Future Requirements
• Additional functionality may be demanded of an PHP application after deployment
• It is important that you design an application that is easily modified and therefore reduces the inefficient practice of recoding
Overall• Creating a solid design before moving on to the
programming phase ensures maintainability and readability.
Step 4 Programming• There are a number of good coding practices than are proposed to enhance the reliability,performance and ease of maintenance of PHP Applications
• Documentation• Commenting
• Commenting is especially lengthy when dealing with lengthy PHP scripts
• With comments present a new developer can skim quickly through the source code, reading just the comments to get an understanding
• Variables should always be logically named in order for developers to understand the function of the variable
Programming• Documentation
• A Naming convention should also be chosen for your variables• By having a prefix developers can quickly determine the type of
information that you are storing in a variable• Using such a notation is useful in PHP, where all variables are declared
using $
Suggested Prefixes for Variable Names
Variable Type Prefix
Integer i
Single sng
Double dbl
String str
Date dt
Boolean bol
Currency cur
Object obj
Debugging Tips PHP• Preventative
• Use an editor that highlights the matching pair of brackets () and {} when one or other is selected allowing you to see mismatched pairs
• Put a comment after each closing brace to indicate which condition is closed
• Reactive • Comment out the nested conditions until the code works
as intended then uncomment pairs until you discover the problem
• You can print out the code and score off matching pairs until you again discover the problem
Modularisation Divide and Conquer• Modularization
• A modularised program is one that is broken down into discrete modules
• Each module serves a sole, unique purpose• Modular programming can be implemented in PHP through
the use of user defined functions• Modularisation can also be implemented through Server Side
Includes• Modularised code is:
• Easy to Write• Easy to Debug• Easy to Understand.• Easy to change
Improving Performance• Performance is key a feature - need to design for
performance up front, or else you get to rewrite your application
Improving Performance• Use Local Variables in Functions
• Local variables are those declared within functions• Within a function local variable access is faster than global variable
access• Use of local variables also tends to make code cleaner
Improving Performance• Session Variables
• Avoid overuse of session variables• Session variables can slow down the application• Alternatively use Cookie for maintaining state
Database Issues• Problem 1: Using MySQL directly
• One common problem is older PHP code using the mysql_ functions to access the database directly
• Problem 2: Not using auto-increment functionality• most modern databases have the ability to create auto numbers on
a per-record basis these should be utilised efficiently
Continued..• Problem 3: Using multiple databases
• Business requirements may dictate the need application in which each table is in a separate database but avoid if at all possible
• Problem 4: Not using relations
Continued..• Problem 5: The n+1 pattern
• Use one query to retrieve the list of all the entities and associated attributes
Dealing with PHP errors• The PHP parser requires that we use a semi-colon at the
end of each PHP statement, otherwise it gets confused
Dealing with PHP errors<html> <head><title>Debug Example</title></head> <body> <?phpecho "<h2>Debugging Workshop</h2>"echo "<p>We are practicing how to fix various errors</p>"; ?> </body></html>
• PHP Parse error: parse error, unexpected T_ECHO, expecting ',' or ';' in c:\Inetpub\wwwroot\MBSEBUS\CHeavin\PHP\dealing errors.php on line 6
Dealing with PHP errors
• There has been a parse error: The PHP interpreter has come across an error and doesn't know what it is supposed to do, so just stops
• It wasn't expecting another echo (T_ECHO) statement, as it hadn't finished the first one
• If the next line after the missing semi-colon was an if statement or a while statement etc then these two would be unexpected (T_IF and T_WHILE etc)
• What the interpreter was expecting was a ' , ' or a ' ; ' - which we know is what was missing
Dealing with PHP errors• Which file this was in i.e. Inetpub\wwwroot\MBSEBUS\CHeavin\
PHP\dealing errors.php - useful if you have included functions from different files
• Which line the PHP interpreter finds a semi-colon in - which is actually the next line - but does act as an indicator in the script as to where the problem lies
Step 5 Marketing (SEO) • How will people find it?
• Is it well optimized for search engines? Use heading tags, bold tags, place your targeted keywords higher up, use alt tags, etc but do not at any time substitute the user-friendly design for a better SEO'd website.
• Pay-per-click marketing
• Try and find some forums which are related to the website you built, become an active user/poster.
• Do not spam at any time.
• Make some flyers, hand them out at busy places in your town/city etc. • This should all be in your business-plan you created before you even
considered Step 1.
Step 6 Analysis of Statistics and Maintenance• You should have a functional website receiving some targeted traffic and converting well. • How well is it really converting?• How many click-throughs you've sent to each merchant• How well a merchant converts them?• How many visitors you received etc. ?
• Maintenance • Disable existing merchants and give other merchants a
better chance to see how they perform• Redesign webpages based on traffic
Blacknight
• http://www.blacknight.com/
• Minimus Hosting 4.95 per month
• Databases• Mysql 4.1• Mysql 5.0• Ms SQL 2005
• Technology• Perl• PHP• .NET 2.0 / 3.5
• Disk space MB: 10GB• Monthly transfer GB: 100
GB
Hosting Ireland
• http://www.hostingireland.ie/• Basic package per annum – 30
Supports:
• PHP 5 enables the addition of dynamic elements to your HTML web pages and automatically insert dates, file information and other HTML documents
• Graphical Web Site Statistics - View real-time usage statistics for your web site, see how many people are visiting your site, where they come from, what search keywords they use to find you and more.
• MySQL Database is the most popular Open Source Database. It is fast, reliable and easy to use. Our control panel features phpMyAdmin which is the most popular web based MySQL manager.