Tuesday, January 8, 2008

DIV Tag

HTML - Div Element(s)
The div tag is nothing more than a container for other tags. Much like the body tag, Div elements are block elements and work behind the scenes grouping other tags together. Use only the following attributes with your div element, anything else should be reserved for CSS. (CSS Tutorial)

id
width
height
title
style
For the purpose of this example, we have included the style attribute in order to color our div tag in order to bring a stronger visualization for our viewers.

HTML Code:

SEARCH LINKS

Google


HTML Div Element:
SEARCH LINKS
Google
Above is a great visual about how a div plays the role of a container for other HTML elements, applying a background color/image is the only real way to visualize your div tags.

HTML - Div Layouts
When HTML first began, web creators only had two choices. A table layout, or frames. The div element provides a 3rd alternative, since a div can contain any/every other type of html element within its beginning and ending tag.

HTML Code:



Content Articles

This paragraph would be your content
paragraph with all of your readable material.




HTML Div Layout:
HOME | CONTACT | ABOUT
Content Articles
This paragraph would be your content paragraph with all of your readable material.

Advanced web developers find div elements to be far easier to work with than tables, adding more content or more links to our previous example might demonstrates why a div is simpler to work with.

Let's add a "LINKS" page to our menu, and another article of content below the existing content.

HTML Code:



Content Articles

This paragraph would be your content
paragraph with all of your readable material.


Content Article Number Two

Here's another content article right here.




HTML Div Layout II:
HOME | CONTACT | ABOUT | LINKS
Content Articles
This paragraph would be your content paragraph with all of your readable material.

Content Article Number Two
Here's another content article right here.

HTML Image Links

HTML - Image Links
Using graphics will liven up that tired, bland-looking text link. To make an image link simply insert an image within the anchor tag. If you do not know how to use the image tag, skip ahead to the image tutorial and come back after you feel comfortable with it.

HTML Code:
a href="http://www.espn.com" target="_blank /a

Image Link:

Notice that by default, many browsers add a small border around image links. This is to quickly deceifer the difference between image links and just ordinary images on a web site. Since this default is different from web browser to web browser it may be best to squelch this ambiguity by setting the border attribute to zero.

HTML Code:


Image Link; No Border:

HTML - Thumbnails
Thumbnails are small size (Kilobytes) pictures that link to the larger, high quality picture. To make a thumbnail save a low-quality version of a picture and make it have smaller dimensions. Now make this low-quality picture into an image link and have it point to the the high-quality picture.

HTML Code:




Thumbnails:

HTML Image

HTML - Images
Images are a staple of any web designer, so it is very important that you understand how to use them properly. Use the tag to place an image on your web page.

HTML Code:


Image:

HTML - Image src
Above we have defined the src attribute. Src stands for source, the source of the image or more appropriately, where the picture file is located. As with links described in a previous lesson, you may use any standard URL to properly point the src attribute to a local or external source.

There are two ways to define the source of an image. First you may use a standard URL. (src=http://www.Tizag.com/pics/htmlT/sunset.gif) As your second choice, you may copy or upload the file onto your web server and access it locally using standard directory tree methods. (src="../sunset.gif") The location of this picture file is in relation to your location of your .html file.

URL Types:
Local Src Location Description
src="sunset.gif" picture file resides in same directory as .html file
src="../sunset.gif" picture file resides in previous directory as .html file
src="../pics/sunset.gif" picture file resides in the pic directory in a previous directory as .html file

A URL cannot contain drive letters, since a src URL is a relational source interpretation based on the location of your .html file and the location of the picture file. Therefore something like src="C:\\www\web\pics\" will not work. Pictures must be uploaded along with your .html file to your web server.

Each method has its pros and cons, for instance using the URL of pictures on other sites poses a problem if the web master(s) of the other site happen to change the physical location of the picture file. Copying the file directly to your web server solves this problem, however, as you continue to upload picture files to your system, you may eventually run short on hard drive space. Use your best judgement to meet your needs.

HTML - Alternative Attribute
The alt attribute specifies alternate text to be displayed if for some reason the browser cannot find the image, or if a user has image files disabled. Text only browsers also depend on the alt attribute since they cannot display pictures.

HTML Code:
Beautiful Sunset

Alternative Text:

HTML - Image Height and Width
To define the height and width of the image, rather than letting the browser compute the size, use the height and width attributes.

HTML Code:


Height and Width:

Above we have defined the src, height and width attributes. By informing the browser of the image dimensions it knows to set aside a place for that image. Without defining an image's dimensions your site may load poorly; text and other images will be moved around when the browser finally figures out how big the picture is supposed to be and then makes room for the picture.

Vertically and Horizontally Align Images
Use the align and valign attributes to place images within your body, tables, or sections.

align (Horizontal)
right
left
center
valign (Vertical)
top
bottom
center

Below is an example of how to align an image to the right of a paragraph.

HTML Code:

This is paragraph 1, yes it is...




The image will appear along the...isn't it?


This is the third paragraph that appears...



Image Wrap Arond:
This is paragraph 1, yes it is. I think this paragraph serves as a nice example to show how this image alignment works.

The image will appear along the right hand side of the paragraph. As you can see this is very nice for adding a little eye candy that relates to the specified paragraph. If we were talking about beautiful tropical sunsets, this picture would be perfect. But we aren't talking about that, so it's rather a waste, isn't it?

This is the third paragraph that appears below the paragraph with the image!

Images as Links
This will be a quick review of the links - image lesson. Images are very useful for links and can be created with the HTML below.

HTML Code:




Image Links:

Now your image will take you to our home page when you click it. Change it to your home page URL.

Thumbnails
Thumbnails are small size (Kilobytes) pictures that link to the larger, high quality picture. To make a thumbnail save a low-quality version of a picture and make it have smaller dimensions. Now make this low-quality picture into an image link and have it point to the the high-quality picture.

HTML Code:




Thumbnails:

HTML Gifs vs. Jpegs
Gifs are best used for banners, clip art, and buttons. The main reason for this is that gifs can have a transparent background which is priceless when it comes to web design. On the down side, gifs are usually larger files, not as compressed as a jpeg, which calls for slow load times and large transfer rates. Gifs are also limited to the 256 color scheme.

Jpegs however, have an unlimited color wheel, and have a high compression rate downsizing your load times and saving hard drive space. Jpegs don't allow for transparent backgrounds, but their size/quality ratio is outstanding. Its best to use Jpegs for photo galleries, or artwork to allow the viewer to catch that extra bit of detail. Avoid Jpegs for graphical design, stick to using them for thumbnails and backgrounds.

HTML Email

Create HTML Email
Making an HTML email link on your page is quick and simple. However, you should know that when you place your email on your website, it is very easy for computer experts to run programs to harvest these types of emails for spamming. If you are going to put your email link on a public website, be sure that you have anti-spam software!

Another option to allow people to send you emails without exposing yourself to massive amounts of spam is to create an HTML form that gathers data from the user and emails it to your email account. We recommend the HTML Form Email that usually reduces the amount of potential spam.

HTML Email Tag
There actually is not a separate HTML tag for creating an HTML email link. Instead you use a standard HTML anchor tag a and set the href property equal to the email adddress, rather than specifying a web URL. This is probably confusing and may take a little while to get used to.

HTML Code:
Email Example

Email Link:
Email Example
Additional HTML Email Code
By adding a couple extra goodies onto the email address in href you can have both the SUBJECT and the BODY of the email automatically populated for your visitors. This is great when receiving emails from a website to an email account that handles more mail than just from that one link on your site.

By defining a uniform subject that people will automatically have when clicking the link you will be able to tell right away whether or not an email came from the website or from another source (as long as your visitors don't mess with the subject that you give them).

Subject - Populates the subject of the email with the information that you provide.
Body - Populates the body of the email with the information that you provide.
HTML Code:

2nd Email Example


Complete Email:
2nd Email Example

HTML Entities

HTML Character Entities
An entity is a fancy term for a symbol. Several symbols such as copyright, trademark, or foreign cash symbols exist outside of the ones you see on your keyboard. In order to display them. In order to display these characters, you need to know 4 parts.

There's three parts to every entity.

HTML Code:

Each begins with a ampersand - &
Then the entities name - copy
And finally a semicolon - ;


Copyright:
Combine © to make - © - Copyright symbol.
Expect complications if you forget to include all three parts of an entity.

Additional Spaces and <>.
As you have may have learned within paragraph and heading tags, browsers will only recognize and format 1 space between words reguardless of how many you may actually type in your coded HTML. An entity exists for placing additional spaces.

Here's an example.

HTML Code:

Everything that goes up, must come     down!



Spaces:
Everything that goes up, must come down!
In HTML we use less than and greater than characters to create tags, so to use them on your web site you will need entities.

HTML Code:


Less than - <

Greater than - >

Body tag - <body>



Less than Greater than:
Less than - <
Greater than - >
Body tag - body tag

HTML Tags

HTML - Font and Basefont
The font tag is used to add style, size, and color to the text on your site. Use the size, color, and face attributes to customize your fonts. Use a basefont> tag to set all of your text to the same size, face, and color.

The font and basefont tags are deprecated and should not be used. Instead, use css styles to manipulate your font. See our CSS Tutorial for more information.

Font Size
Set the size of your font with size. The range of accepted values is from 1(smallest) to 7(largest).The default size of a font is 3.

HTML Code:


Here is a size 5 font



Font Size:
Here is a size 5 font.
Font Color
Set the color of your font with color.

HTML Code:
font color="#990000" This text is hexcolor #990000/font


font color="red" This text is red /font

Font Color:
This text is hexcolor #990000
This text is red
Font Face
Choose a different font face using any font you have installed. Be aware that if the user viewing the page doesn't have the font installed, they will not be able to see it. Instead they will default to Times New Roman. An option is to choose a few that are similar in appearance.

HTML Code:


This paragraph
has had its font...



Font Face:
This paragraph has had its font formatted by the font tag!
Basefont - Set a Solid Base
With the basefont tag you will be able to set the default font for your web page. We highly recommend specifying a basefont if you plan on using any font with HTML. Below is the correct way to set your basefont.

HTML Code:

This paragraph has had its font...


This paragraph has had its font...


This paragraph has had its font...




Base Font:
This paragraph has had its font formatted by the basefont tag!
This paragraph has had its font formatted by the basefont tag!
This paragraph has had its font formatted by the basefont tag!

However, the use of basefont is deprecated, which means it may not be supported sometime in the future. The perfectly correct way to change your sites basefont is to set it with CSS. Check out our CSS Tutorial for more information.

Attribute Review
Attributes:
Attribute= "Value" Description size= "Num. Value 1-7" Size of your text, 7 is biggest color= "rgb,name,or hexidecimal" Change font color face= "name of font" Change the font type

Beautiful First Letter Style
Customize your fonts to achieve any of your desired looks.

HTML Code:

Customize
your font to achieve a desired look.



Beauty:
Customize your font to achieve a desired look.

HTML - Links and Anchors
The web got its spidery name from the plentiful connections between web sites. These connections are made using anchor tags to create links. Text, Images, and Forms may be used to create these links.

HTML - Hypertext Reference (href)
The href attribute defines reference that the link refers to. Basically this is where the user will be taken if they wish to click this link.

Hypertext references can be Internal, Local, or Global.
Internal - Links to anchors on the current page
Local - Links to other pages within your domain
Global - Links to other domains outside of your site
HTML Code:
Internal - href="#anchorname"
Local - href="../pics/picturefile.jpg"
Global - href="http://www.tizag.com/"

HTML - Text Links
Use the tags to define the start and ending of an anchor. Decide what type of href attribute you need and place this attribute into the opening tag. The text you place between the opening and closing tags will be shown as the link on a page. Use the demonstration below as a reference.

HTML Code:
Tizag Home
ESPN Home
Yahoo Home

Global Link:
Tizag Home ESPN Home Yahoo Home
HTML - Link Targets
The target attribute defines whether to open the page in a separate window, or to open the link in the current browser window.

HTML Code:
target=" _blank" Opens new page in a new browser window _self" Loads the new page in current window _parent" Loads new page into a frame that is superior to where the link lies _top" Loads new page into the current browser window, cancelling all frames

The example below shows how you would link to ESPN.COM, a popular sports web site. The target attribute is added to allow the browser to open ESPN in a new window, so that the viewer can remain at our web site. Here's the example.

HTML Code:
ESPN.COM

_blank Target:
ESPN.COM
HTML - Anchors
To link to sections of your existing page a name must be given to the anchor. In the example below, we've created a mini Table of Contents for this page. By placing blank anchors just after each heading, and naming them, we can then create reference links to those sections on this page as shown below.

First, the headings of this page contain blank, named anchors. They look like this.

Tizag's Own Code:

HTML Links and Anchors


HTML Text Links


HTML Email



Now create the reference links, placing the pound symbol followed by the name of the anchor in the href of the new link.

Anchor Code:
Go to the Top
Learn about Text Links
Learn about Email Links

Local Links:
Go to the Top
Learn about Text Links
Learn about Email Links
HTML - Email Links
Creating an email link is simple. If you want somebody to mail you about your site a good way to do it is place an email link with a subject already in place for them.

HTML Code:
Email@tizag.com

Email Links:
Email@tizag.com
In some circumstances it may be necessary to fill in the body of the Email for the user as well.

HTML Code:

Email@tizag.com


Complete Email:
Email@tizag.com
HTML - Download Links
Placing files available for download is done in exactly the same fashion as placing text links. Things become complicated if we want to place image links available for download. The best solution for images is to use a thumbnail link that we discuss in the next lesson.

HTML Code:
Text Document

Download a Text Document:
Text Document
HTML - Default Links; Base
Use the base tag in the head element to set a default URL for all links on a page to go to. It's always a good idea to set a base tag just incase your links become bugged somewhere down the line. Usually set your base to your home page.

HTML Code:
base href="http://www.tizag.com/"

HTML Color Coding

HTML Color Coding System - Color Names
There are 3 different methods to set color. The simplest being the Generic terms of colors. Examples: black, white, red, green, and blue. Generic colors are preset HTML coded colors where the value is simply the name of each color. Here is a sample of the most widely supported colors and their respective name values.

The 16 Basic Colors:
Black Gray Silver White
Yellow Lime Aqua Fuchsia
Red Green Blue Purple
Maroon Olive Navy Teal

HTML Coloring System - RGB Values
We do not recommend that you use RGB for safe web design because non-IE browsers do not support HTML RGB. However, if you plan on learning CSS then you should glance over this topic.

RGB stands for Red, Green, Blue. Each can have a value from 0 (none of that color) to 255 (fully that color). The format for RGB is - rgb(RED, GREEN, BLUE), just like the name implies. Below is an example of RGB in use, but if you are not using a browser that supports it, do not worry, that is just one of the problems with HTML RGB.

Red, Green, and Blue Values:
bgcolor="rgb(255,255,255)" White
bgcolor="rgb(255,0,0)" Red
bgcolor="rgb(0,255,0)" Green
bgcolor="rgb(0,0,255)" Blue

HTML Coloring System - Hexadecimal
The hexadecimal system is complex and difficult to understand at first. Rest assured that the system becomes much, MUCH easier with practice and as a blossoming web developer, it is critical to understand hexadecimals to be capable of using them in your own web publications. They are far more reliable and widely compatible among web browsers and are the standard for colors on the internet.

A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red value, the next two are a green value(GG), and the last are the blue value(BB).

Here's a hexadecimal you might see in an HTML document.

My First Hexadecimal:
bgcolor="#RRGGBB"

HTML Color Code - Breaking the Code
The following table shows how letters are incorporated into the hexadecimal essentially extending the numbers system to 16 values. Hang in there it all makes sense shortly.

Hexadecimal Color Values:
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F

So use letters as numbers?We will answer this question as we dive into the converting hexadecimals to regular numbers. Let's have a look at real Hexadecimal.

A Real Hexadecimal:
bgcolor="#FFFFFF"

The letter "F" is the maximum amount we can send each color and as you may deduce, this color (#FFFFFF) represents the color white. A formula exists to calculate the numeric equivalent of a hexadecimal.

Hexadecimal Formula:
(15 * 16) + (15) = 255

The formula is real simple. Take the first value (F) or 15 multiply it by 16 and add it to the second value, 15. The value 255 is the maximum allowed for any primary color.

Let's try another one.

Example 2:
bgcolor="#CC7005"

CC(RR - Red)
(12 * 16) + (12) = 204
70(GG - Green)
(7 * 16) + (0) = 112
05(BB - Blue)
(0 * 16) + (5) = 5

Hexadecimals are the best choice for compatible web development because of their consistency between browsers. Even the most minor of change in color can throw your entire site out of whack, so be sure to check your site in a number of browsers. If you want to be absolutely sure your colors will not change, use paired hex values for color. Examples: "#0011EE", "#44HHFF", or "#117788". These are called True Colors, since they will stay true in hue from browser to browser.

HTML

HTML - Attributes
Attributes are used to amplify tags. What we mean by amplify is that when a web browser interprets a tag, it will also search for set attributes and then display the element (tags+attributes) in its entirety. At some point you may want to give your body element a background color or perhaps change the width of a table. All of these things and more can be achieved using Attributes.

Many HTML tags have a unique set of their own attributes. These will be discussed as each tag is introduced throughout the tutorial. Right now we want to focus on a set of generic attributes that can be used with just about every HTML Tag in existence.

Attributes are placed within the opening tag and they follow a precise syntax (format).

HTML - Class or ID Attribute
The class and id attributes are nearly identical. They play no direct role in formatting your elements but rather serve behind the scenes for scripting and Cascading Style Sheets (CSS). The role of classification and identifying elements will become more apparent as your learn CSS.

The idea is that you can classify or id certain a tag and later format the tag using Cascading Style Sheets. It becomes necessary when you have two or more of the same element on a page (like a

tag) but want them to be different in appearance.

HTML Code:

Paragraph type 1 Italics


Paragraph type 2 Bold



Classification Attributes:
Paragraph type 1 Italics
Paragraph type 2 Bold
HTML - Name Attribute
Name is much different than id and class. By allotting a name to an element, that name becomes a scripting variable for scripting languages such as Javascript, ASP, and PHP. The name attribute is seen most often with forms and other user-input elements.

HTML Code:


The Name Game:

This attribute has no effect on the display of the text field, but behind the scenes it plays a huge identification role.

HTML - Title Attribute
This is a neat little perhaps, forgotten attribute. This attribute titles an element and adds a tiny text pop-up to any HTML element. Much like the text pop-ups of word processing programs, these attributes should not be forgotten. You may title an element anything you would like, the effects of this attribute are not seen until you hover your mouse over the element for a few seconds.

HTML Code:

Titled Heading Tag



Title Attribute:
Titled Heading Tag
Hover your mouse over the display heading to see the magic of the title attribute! This provides your web site with some user interaction which is priceless. Do not overlook the title attribute.

HTML - Align Attribute
If you wish to change the horizontal location of your elements you may do so using the align attribute. You may align things left, right, or center. By default most elements are automatically aligned left unless otherwise specified.

HTML Code:

Centered Heading



Display:
Centered Heading
HTML Code:

Left aligned heading


Centered Heading


Right aligned heading



Display:
Left aligned heading
Centered heading
Right aligned heading

Ajax Techniques

Ajax - Javascript Techniques
The real trick of Ajax is updating a segment of the page without actually having to reload the entire page. This little trick is often done by utilizing a Javascript property known as innerHTML. Each HTML element on a page has an innerHTML associated with it that can be changed at any time. For us, we need to update it when our ajax-example.php script has finished executing.

Updating the order.html Page
First we need to create a new div on this page that will contain the results of the query. After we have that in place we can update the div's innerHTML with the information returned by ajax-example.php. Remember that this result is stored inside ajaxRequest.responseText.

order.html HTML/Javascript Code:






Max Age:

Max WPM:


Sex:


Your result will display here

Ajax

Ajax - MySQL Database
We already know how to run an external PHP script with AJAX, so let's take it to the next level and pull some data down from a MySQL database. Our "order.html" file and PHP script will have to be updated and we also need to make a new database.

Create the MySQL Table
To clearly illustrate how easy it is to access information from a database using Ajax, we are going to build MySQL queries on the fly and display the results on "order.html".

Create a new database or use an existing one and then import the table ajax_example.sql to that database. This sql file will create the table ajax_example and insert all the data rows. The table has four columns:

ae_name - The name of the person
ae_age - Person's age
ae_sex - The gender of the person
ae_wpm - The words per minute that person can type
Update order.html
We want to be able to build queries from our HTML file, so there are a few form elements that will need to be added. The three inputs we are going to implement are:

Maximum Age (Text Input) - Let the user select the maximum age to be returned.
Maximum WPM (Text Input) - Let the user select the maximum wpm to returned.
Gender (Select Input) - Let the user select the gender of a valid person.
order.html HTML/Javascript Code:








Max Age:

Max WPM:


Sex:





If the new Javascript code is foreign to you, be sure to check out our lesson on Javascript's getElementById Function.

With our new Javascript code
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
we have built a query string to pass along the information from our HTML form to our PHP script.

Ajax - Passing Variables via Query String
A query string is a way of passing information by appending data onto the URL. You may have often seen it on the web, it's all the information that appears after a question mark "?". When you submit a form using GET it builds a query string, all we're doing here is manually building our own.

http://www.tizag.com/somescript.php?variable1=value1&variable2=value2
The left side of the equals operator is the variable name and the right side is the variable's value. Also, each variable is separated with an ampersand &.

For example, if we wanted to send the variables age, sex, and wpm with values 20, f, 40 to our PHP script ajax-example.php then our URL would look like:

http://www.tizag.com/ajax-example.php?age=20&sex=f&wpm=40
Now we need to build a new PHP script to take these variables and run a MySQL query for us.

Ajax - Create ajax-example.php Script
We already changed the destination URL in our ajaxRequest.open method, now we need to make a script to grab those variables from the query string and execute a MySQL Query. We're also going to use a special function mysql_real_escape_string to prevent any harmful user input from doing something they aren't supposed to (we're going to take steps against SQL Injection).

ajax-example.php Code:
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
$query .= " AND ae_age <= $age";
if(is_numeric($wpm))
$query .= " AND ae_wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

//Build Result String
$display_string = "";
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";
$display_string .= "";

}
echo "Query: " . $query . "
";
$display_string .= "
NameAgeSexWPM
$row[ae_name]$row[ae_age]$row[ae_sex]$row[ae_wpm]
";
echo $display_string;
?>

PHP Advanced

PHP Date - Robust Dates and Times
While PHP's date() function may seem to have an overwhelming amount of options available, isn't it always better to have more choices than not enough? With PHP's date function you format timestamps, so they are more human readable.
This lesson will teach you how to display the current time, formating PHP's timestamp, and show you all the various date arguments for reference purposes.
PHP Date - The Timestamp
The date function always formats a timestamp, whether you supply one or not. What's a timestamp? Good question!
Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.
PHP Date - What Time Is It?
The date function uses letters of the alphabet to represent various parts of a typical date and time format. The letters we will be using in our first example are:
d: The day of the month. The type of output you can expect is 01 through 31.
m: The current month, as a number. You can expect 01 through 12.
y: The current year in two digits ##. You can expect 00 through 99
We'll tell you the rest of the options later, but for now let's use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP.
However, other characters like a slash "/" can be inserted between the letters to add additional formatting. We have opted to use the slash in our example.
PHP Code:
echo date("m/d/y");
?>
If the 2010 Winter Olympics were just finishing up, you would see something like:
Display:
02/27/10
Be sure to test this out on your own PHP enabled server, it's really great to see the instant results available with PHP date!
PHP Date - Supplying a Timestamp
As our first example shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional.
This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime.
Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.
mktime(hour, minute, second, month, day, year, daylight savings time)
PHP Code:
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
echo "Tomorrow is ".date("m/d/y", $tomorrow);
?>
Notice that we used one letter at a time with the function date to get the month, day and year. For example the date("m") will return the month's number 01-12.
If we were to run our new script just after the 2010 Winter Olympics our display would look like:
Display:
Tomorrow is 02/28/10
PHP Date - Reference
Now that you know the basics of using PHP's date function, you can easily plug in any of the following letters to format your timestamp to meet your needs.
Important Full Date and Time:
r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")
Time:
a: am or pm depending on the time
A: AM or PM depending on the time
g: Hour without leading zeroes. Values are 1 through 12.
G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
h: Hour with leading zeroes. Values 01 through 12.
H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
i: Minute with leading zeroes. Values 00 through 59.
s: Seconds with leading zeroes. Values 00 through 59.
Day:
d: Day of the month with leading zeroes. Values are 01 through 31.
j: Day of the month without leading zeroes. Values 1 through 31
D: Day of the week abbreviations. Sun through Sat
l: Day of the week. Values Sunday through Saturday
w: Day of the week without leading zeroes. Values 0 through 6.
z: Day of the year without leading zeroes. Values 0 through 365.
Month:
m: Month number with leading zeroes. Values 01 through 12
n: Month number without leading zeroes. Values 1 through 12
M: Abbreviation for the month. Values Jan through Dec
F: Normal month representation. Values January through December.
t: The number of days in the month. Values 28 through 31.
Year:
L: 1 if it's a leap year and 0 if it isn't.
Y: A four digit year format
y: A two digit year format. Values 00 through 99.
Other Formatting:
U: The number of seconds since the Unix Epoch (January 1, 1970)
O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours
We suggest that you take a few minutes to create several timestamps using PHP's mktime function and just try out all these different letters to get your feet wet with PHP's date function.

PHP Sessions - Why Use Them?
As a website becomes more sophisticated, so must the code that backs it. When you get to a stage where your website need to pass along user data from one page to another, it might be time to start thinking about using PHP sessions.
A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. This makes it quite a problem for tasks like a shopping cart, which requires data(the user's selected product) to be remembered from one page to the next.
PHP Sessions - Overview
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.
It is important to ponder if the sessions' temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.
Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.
Note:If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug.
Starting a PHP Session
Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.
PHP Code:
session_start(); // start up your PHP session!
?>
This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user's session.
Storing a Session Variable
When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.
PHP Code:
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>
Display:
Pageviews = 1
In this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.
PHP Sessions: Using PHP's isset Function
Now that you know can easily store and retrieve data from the $_SESSION array, we can now explore some of the real functionality of sessions. When you create a variable and store it in a session, you probably want to use it in the future. However, before you use a session variable it is necessary that you check to see if it exists already!
This is where PHP's isset function comes in handy. isset is a function that takes any variable you want to use and checks to see if it has been set. That is, it has already been assigned a value.
With our previous example, we can create a very simple pageview counter by using isset to check if the pageview variable has already been created. If it has we can increment our counter. If it doesn't exist we can create a pageview counter and set it to one. Here is the code to get this job done:
PHP Code:
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;

echo "views = ". $_SESSION['views'];
?>
The first time you run this script on a freshly opened browser the if statement will fail because no session variable views would have been stored yet. However, if you were to refresh the page the if statement would be true and the counter would increment by one. Each time you reran this script you would see an increase in view by one.
Cleaning and Destroying your Session
Although a session's data is temporary and does not require that you explicitly clean after yourself, you may wish to delete some data for your various tasks.
Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart.
PHP Code:
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?>
You can also completely destroy the session entirely by calling the session_destroy function.
PHP Code:
session_start();
session_destroy();
?>
Destroy will reset your session, so don't call that function unless you are entirely comfortable losing all your stored session data!


PHP Cookies - Background
Cookies have been around for quite some time on the internet. They were invented to allow webmaster's to store information about the user and their visit on the user's computer.
At first they were feared by the general public because it was believed they were a serious privacy risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are worse things to worry about and partly because all of the "trustworthy" websites now use cookies.
This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as explaining the various options you can set with your cookie.
Creating Your First PHP Cookie
When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):
1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!
2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.
In this example we will be creating a cookie that stores the user's last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie's expiration date to two months in the future!
PHP Code:
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
?>
Don't worry if you can't follow the somewhat involved date calculations in this example. The important part is that you know how to set a cookie, by specifying the three important arguments: name, value and expiration date.
Retrieving Your Fresh Cookie
If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!
PHP Code:
if(isset($_COOKIE['lastVisit']))
$visit = $_COOKIE['lastVisit'];
else
echo "You've got some stale cookies!";

echo "Your last visit was - ". $visit;
?>
This handy script first uses the isset function to be sure that our "lastVisit" cookie still exists on the user's PC, if it does, then the user's last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this:
Display:
Your last visit was - 11:48 - 02/28/08

PHP String

PHP - String Position - strpos
Being able to manipulate strings is a valuable skill, especially in PHP. You'll most likely come across a programming problem that requires you to find some data in a string. The beginning of a lot of your string manipulation expertise will begin with the strpos function, which allows you to find data in your string.
Searching a String with strpos
The way strpos works is it takes some string you want to search in as its first argument and another string, which is what you are actually searching for, as the second argument. If the function can find a search match, then it will return the position of the first match. However, if it can't find a match it will return false.
To make this function crystal clear, lets search a numbered, in-order string, for the number five.
PHP Code:
$numberedString = "1234567890"; // 10 numbers from 1 to 0

$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
Display:
The position of 5 in our string was 4
Notice that the position is 4, which may seem confusing at first, until you realize that PHP starts counting from 0.
The number 1 - Position 0 - No match
The number 2 - Position 1 - No match
The number 3 - Position 2 - No match
The number 4 - Position 3 - No match
The number 5 - Position 4 - Match
Although we only searched for a single character, you can use this function to search for a string with any number of characters. Also, it is important to note that this function will return the position of the start of the first match. So if we had searched the same string for "567890" we would again find a match and position 4 because that is where the match starts.
Finding All Occurrences in a String with Offset
One of the limitations of strpos is that it only returns the position of the very first match. If there are 5,000 other matches in the string you would be none the wiser, unless you take action!
There is a third (optional) argument to strpos that will let you specify where to begin your search of the string. If you were to store the position of the last match and use that + 1 as an offset, you would skip over the first match and be find the next one.
PHP Code:
$numberedString = "1234567890123456789012345678901234567890";

$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
$fivePos2 = strpos($numberedString, "5", $fivePos + 1);
echo "
The position of the second 5 was $fivePos2";
Display:
The position of 5 in our string was 4
The position of the second 5 was 14
By taking the first match's position of 4 and adding 1 we then asked strpos to begin searching after the last match. The string it was actually searching after computing the offset was: 6789012345... Letting us find the second 5 in the string.
If we use our knowledge of PHP While Loops we can find every single 5 in our string numberedString with just a few lines of code.
PHP Code:
$numberedString = "1234567890123456789012345678901234567890";
$offset = 0; // initial offset is 0
$fiveCounter = 0;

// First check if there is a "5" at position 0.
if(strpos($numberedString, "5") == 0){
$fiveCounter++;
echo "
Five #$fiveCounter is at position - 0";
}

// Check the rest of the string for 5's
while($offset = strpos($numberedString, "5", $offset + 1)){
$fiveCounter++;
echo "
Five #$fiveCounter is at position - $offset";
}
Display:
Five #1 is at position - 4
Five #2 is at position - 14
Five #3 is at position - 24
Five #4 is at position - 34
That conditional statement in our while loop may look a little intimidating, but not if you break it down.
$offset = strpos($numberedString, "5", $offset + 1) - This is our conditional statement for our PHP While Loop. If this ever is false the while loop will stop running. This conditional statement always runs before each pass through the while loop.
strpos($numberedString, "5", $offset + 1) - This is the same code we used in a previous example. We are going to search our string numberedString for the number 5 and use the last match's value (stored in $offset) + 1 to skip over the last match. The first $offset we use has a value of 0, so that we start at the beginning of the string.
$offset = strpos(... We are going to store the location returned by strpos into $offset so that we can skip this match the next time the while loop runs through the code. If strpos ever fails to find a match then this will be set to false making our while loop stop executing.
PHP str_replace Function
Another key tool to have in your programming toolbox is the ability to quickly replace parts of a PHP string with new values. The str_replace function is similar to a word processor's "Replace All" command that lets you specify a word and what to replace it with, then replaces every occurrence of that word in the document.
str_replace Parameters
str_replace has three parameters that are required for the function to work properly. str_replace(search, replace, originalString).
1. search - This is what you want to search your string for. This can be a string or an array.
2. replace - All matches for search will be replaced with this value. This can be a string or an array.
3. originalString - This is what search and replace will be operating on. The str_replace function will return a modified version of originalString when it completes.
str_replace Simple Example
Imagine we are working at a school district and need to create a webpage for the students' parents. The webpage has an introduction string that we need to customize depending on if the student is male or female. With str_replace this is mighty easy.
PHP Code:
//string that needs to be customized
$rawstring = "Welcome Birmingham parents. Your replaceme is a pleasure to have!";

//male string
$malestr = str_replace("replaceme", "son", $rawstring);

//female string
$femalestr = str_replace("replaceme", "daughter", $rawstring);

echo "Son: ". $malestr . "
";
echo "Daughter: ". $femalestr;
Display:
Son: Welcome Birmingham parents. Your son is a pleasure to have!
Daughter: Welcome Birmingham parents. Your daughter is a pleasure to have!
With these two gender customized strings created we could then provide a more engaging experience for the student's parents when they logged into the school website with their kid's credentials.
str_replace Arrays: Multiple Replaces in One
In the last example we only needed to replace one word replaceme in our string, but what if we wanted to replace many words? We could just use the function multiple times to get the job done, or we could create an array of placeholders and a second array of replace values to get it all done in one function call.
The key thing to understand with this technique is that you are creating two arrays that will be used to swap values. The first item in placeholders will be replaced by the first item in the replace values, the second item of placeholders replaced with the second in replace values and so on and so forth.
Let's extend our simple example to be a complete form letter addressed to a student's parents.
PHP Code:
//string that needs to be customized
$rawstring = "Welcome Birmingham parent!

Your offspring is a pleasure to have!
We believe pronoun is learning a lot.

The faculty simple adores pronoun2 and you can often hear
them say \"Attah sex!\"
";

//placeholders array
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
//male replace values array
$malevals = array('son', 'he', 'him', 'boy');
//female replace values array
$femalevals = array('daughter', 'she', 'her', 'girl');

//male string
$malestr = str_replace($placeholders, $malevals, $rawstring);

//female string
$femalestr = str_replace($placeholders, $femalevals, $rawstring);

echo "Son: ". $malestr . "
";
echo "Daughter: ". $femalestr;
Display:
Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores he2 and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores she2 and you can often hear them say "Attah girl!"
Notice: there is a bug in this code. The placeholder pronoun2 did not get replaced in the way we intended (our strings have he2 and she2 instead of him and her). This is because all instances of pronoun were replaced first and the pronoun in pronoun2 was replaced at this time with he or she, making he2 or she2. When it was pronoun2's turn to be replaced, there were no matches to be found, so our string has no him or her.
To fix this bug you could simply make sure that pronoun2 comes first in the placeholders array and by updating the values of the male and female replace values to reflect this.
PHP Code:
// ...snip
//placeholders array
$placeholders = array('offspring', 'pronoun2', 'pronoun', 'sex');
//male replace values array
$malevals = array('son', 'him', 'he', 'boy');
//female replace values array
$femalevals = array('daughter', 'her', 'she', 'girl');
//snip...
Display:
Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores him and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores her and you can often hear them say "Attah girl!"

PHP substr_replace Function
The function substr_replace introduces some additional functionality to compliment str_replace. substr_replace is a more mathematically based replace function, which relies on starting points and lengths to replace parts of strings, as opposed to searching and replacing.
substr_replace's Four Parameters
There are three required parameters for the substr_replace function (original string, replacement string, starting point) and one that's optional (length).
1. original string - This is your original string that will be operated on.
2. replacement string - This string will be used to replace everything in the string from the starting point to the ending point (specified by length).
3. starting point - This is the place in the original string that will be used to mark the replacement's beginning. A negative value specifies the number of characters from the end of the string.
4. optional length - How many characters from the original string will be replaced. If no length is specified then the end of the string is used. If a value of 0 is used then no characters will be replaced and an insert is performed. A negative value specifies the number of characters from the end of the string.
substr_replace On Your Mark
This example of substr_replace shows what happens when you omit the length parameter at various starting points.
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);

//Echo each string
echo "Original String: $original
";
echo "Starting Point 5: $sp5
";
echo "Starting Point 12: $sp12
";
echo "Starting Point 0: $sp0
";
echo "Starting Point -1: $spneg1 ";
Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Starting Point 5: ABC12Five
Starting Point 12: ABC123 HelloTwelve
Starting Point 0: Zero
Starting Point -1: ABC123 Hello Mr. Cow! DEF32Negative 1
As you can see, when you don't specify the fourth parameter, length, everything after the starting point is replaced by the second parameter replacement string.
Note: The first replacement occurred at position 5, which in $original was the character 3. This 3 and everything onward was replaced with the replacement string. Remember that you start counting character to begin from zero. The $original string could be labeled as so:
Letter A - Position 0
Letter B - Position 1
Letter C - Position 2
Letter 1 - Position 3
Letter 2 - Position 4
Letter 3 - Position 5
substr_replace Specifying a Length
If you want to get any sort of precision out of this function you're going to have to get into the nitty gritty of specifying the exact length of characters you want replaced in your original string.
Imagine that you want to get rid of those ugly pseudo references (ABC123, DEF321) at the beginning and end of the string. Since both of those strings are a length of 6 and we know one is at the very beginning of the string and the other is at the very end of the string we should probably use a starting point of 0 for ABC123 and a value of -6 for DEF321. By having a replacement string of nothing "" we can do something similar to select and delete that we often do in a word processor.
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";

//remove ABC123 and store in $cleanedstr
$cleanedstr = substr_replace($original, "", 0, 6);
//remove DEF321 from $cleanedstr
$cleanedstr2 = substr_replace($cleanedstr, "", -6, 6);

//Echo each string
echo "Original String: $original
";
echo "Clean #1: $cleanedstr
";
echo "Clean #2: $cleanedstr2";
Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Clean #1: Hello Mr. Cow! DEF321
Clean #2: Hello Mr. Cow!
Make sure that you play around with this function some on your own so you can get a feel for how the starting point and length parameters effect this function.
substr_replace Perform an Insert
By setting the length parameter to zero you can stop substr_replace from removing anything from the original string and just add to it. If we wanted to add a second and third person to our $original string we would want to do this insert operation. Note: instead of counting the characters we've used a couple other PHP functions to figure out the starting positions for us.
PHP Code:
//string that needs to be customized
$original = "Hello Mr. Cow!";

// Get the position of Mr. Cow
$cowpos = strpos($original, "Mr. Cow");

// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");

// Insert Mrs. Bear after Mr. Cow
$mrsbear = substr_replace($original, " and Mrs. Bear", $cowpos_end, 0);

// Insert Sensei Shark before Mr. Cow
$senseishark = substr_replace($mrsbear, "Sensei Shark, ", $cowpos, 0);


//Echo each string
echo "Original String: $original
";
echo "After Mrs. Bear: $mrsbear
";
echo "After Sensei Shark: $senseishark";
Display:
Original String: Hello Mr. Cow!
After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!
After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!
We snuck a new function strlen into that example, but it isn't that complicated of a function, as it stands for "string length."
$cowpos_end = $cowpos + strlen("Mr. Cow");
The strlen function takes a string and then counts up how many characters are in it then returns that number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where the end point is!
PHP - String Capitalization Functions
If you've ever wanted to manipulate the capitalization of your PHP strings, then this lesson will be quite helpful to you. PHP has three primary capitalization related functions: strtoupper, strtolower and ucwords. The function names are pretty self-explanatory, but why they are useful in programming might be new to you.
Converting a String to Upper Case - strtoupper
The strtoupper function takes one argument, the string you want converted to upper case and returns the converted string. Only letters of the alphabet are changed, numbers will remain the same.
PHP Code:
$originalString = "String Capitalization 1234";

$upperCase = strtoupper($originalString);
echo "Old string - $originalString
";
echo "New String - $upperCase";
Display:
Old string - String Capitalization 1234
New String - STRING CAPITALIZATION 1234
One might use this function to increase emphasis of a important point or in a title. Another time it might be used with a font that looks very nice with all caps to fit the style of the web page design.
A more technical reason would be to convert two strings you are comparing to see if they are equal. By converting them to the same capitalization you remove the possibility that they won't match simply because of different capitalizations.
Converting a String to Lower Case - strtolower
The strtolower function also has one argument: the string that will be converted to lower case.
PHP Code:
$originalString = "String Capitalization 1234";

$lowerCase = strtolower($originalString);
echo "Old string - $originalString
";
echo "New String - $lowerCase";
Display:
Old string - String Capitalization 1234
New String - string capitalization 1234
Capitalizing the First Letter - ucwords
Titles of various media types often capitalize the first letter of each word and PHP has a time-saving function that will do just this.
PHP Code:
$titleString = "a title that could use some hELP";

$ucTitleString = ucwords($titleString);
echo "Old title - $titleString
";
echo "New title - $ucTitleString";
Display:
Old title - a title that could use some hELP
New title - A Title That Could Use Some HELP
Notice that the last word "hELP" did not have the capitalization changed on the letters that weren't first, they remained capitalized. If you want to ensure that only the first letter is capitalized in each word of your title, first use the strtolower function and then the ucwords function.
PHP Code:
$titleString = "a title that could use some hELP";

$lowercaseTitle = strtolower($titleString);
$ucTitleString = ucwords($lowercaseTitle);
echo "Old title - $titleString
";
echo "New title - $ucTitleString";
Display:
Old title - a title that could use some hELP
New title - A Title That Could Use Some Help


PHP - String Explode
The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence you could ask explode to use the sentence's spaces " " as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence "Hello, I would like to lose weight." would look like this after explode got done with it:
1. Hello,
2. I
3. would
4. like
5. to
6. lose
7. weight.
The dynamite (the space character) disappears, but the other stuff remains, but in pieces. With that abstract picture of the explode function in mind, lets take a look at how it really works.
The explode Function
The first argument that explode takes is the delimiter (our dynamite) which is used to blow up the second argument, the original string. explode returns an array of string pieces from the original and they are numbered in order, starting from 0. Lets take a phone number in the form ###-###-#### and use a hyphen "-" as our dynamite to split the string into three separate chunks.
PHP Code:
$rawPhoneNumber = "800-555-5555";

$phoneChunks = explode("-", $rawPhoneNumber);
echo "Raw Phone Number = $rawPhoneNumber
";
echo "First chunk = $phoneChunks[0]
";
echo "Second chunk = $phoneChunks[1]
";
echo "Third Chunk chunk = $phoneChunks[2]";
Display:
Raw Phone Number = 800-555-5555
First chunk = 800
Second chunk = 555
Third Chunk chunk = 5555
explode Function - Setting a Limit
If you want to control the amount of destruction that explode can wreak on your original string, consider using the third (optional) argument which allows you to set the number of pieces explode can return. This means it will stop exploding once the number of pieces equals the set limit. Below we've blown up a sentence with no limit and then with a limit of 4.
PHP Code:
$someWords = "Please don't blow me to pieces.";

$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
echo "Piece $i = $wordChunks[$i]
";
}

$wordChunksLimited = explode(" ", $someWords, 4);
for($i = 0; $i < count($wordChunksLimited); $i++){
echo "Limited Piece $i = $wordChunksLimited[$i]
";
}
Display:
Piece 0 = Please
Piece 1 = don't
Piece 2 = blow
Piece 3 = me
Piece 4 = to
Piece 5 = pieces.
Limited Piece 0 = Please
Limited Piece 1 = don't
Limited Piece 2 = blow
Limited Piece 3 = me to pieces.


PHP - Array implode
The PHP function implode operates on an array and is known as the "undo" function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string.
PHP implode - Repairing the Damage
The first argument of implode is the string of characters you want to use to join the array pieces together. The second argument is the array (pieces).
PHP Code:
$pieces = array("Hello", "World,", "I", "am", "Here!");

$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i < count($pieces); $i++){
echo "Piece #$i = $pieces[$i]
";
}
echo "Glued with Spaces = $gluedTogetherSpaces
";
echo "Glued with Dashes = $gluedTogetherDashes";
Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!
The implode function will convert the entire array into a string and there is no optional argument to limit this as there was in the explode function.

PHP Files

PHP - Files
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.
This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP!
PHP - Files: Be Careful
When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
PHP - Files: Overview
The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

PHP - File Create
Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.
PHP - Creating Confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
PHP - How to Create a File
The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
1. $ourFileName = "testFile.txt";
Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
3. fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.
PHP - Permissions
If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.
In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.
PHP - File Open
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important function and see what it has to offer.
PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.
Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
Write: 'w'
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.
Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.
A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.
PHP - Explanation of Different Types of fopen
These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.
PHP - File Open: Advanced
There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.
Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter
Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).
Pseudo PHP Code:
$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);



PHP - File Close
The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open file running around on your server taking up resources and causing mischief!
PHP - File Close Description
In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!
PHP - File Close Function
In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.


PHP - File Write
Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it's logically called fwrite.
PHP - File Open: Write
Before we can write information to our test file we have to use the function fopen to open the file for writing.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
PHP - File Write: fwrite Function
We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go!
Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner. After we finished writing we closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this:
Contents of the testFile.txt File:
Bobby Bopper
Tracy Tanner
PHP - File Write: Overwriting
Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing file testFile.txt and write some new data into it.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);
If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
In the next lesson we will show you how to get information out of a file by using PHP's read data functions!


PHP - File Read
My apologies for taking so long to actually get to the point where you get information from files. In this lesson we will teach you how to read data from a file using various PHP functions.
PHP - File Open: Read
Before we can read information from a file we have to use the function fopen to open the file for reading. Here's the code to read-open the file we created in the PHP File Write lessons.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
The file we created in the last lesson was named "testFile.txt". Your PHP script that you are writing should reside in the same directory as "text.txt". Here are the contents of our file from File Write.
testFile.txt Contents:
Floppy Jalopy
Pointy Pinto
Now that the file is open, with read permissions enabled, we can get started!
PHP - File Read: fread Function
The fread function is the staple for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
Display:
Flopp
The first five characters from the testFile.txt file are now stored inside $theData. You could echo this string, $theData, or write it to another file.
If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Display:
Floppy Jalopy Pointy Pinto
Note: It is all on one line because our "testFile.txt" file did not have a
tag to create an HTML line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.
PHP - File Read: gets Function
PHP also lets you read a line of data at a time from a file with the gets function. This can or cannot be useful to you, the programmer. If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.
Lucky for us our "testFile.txt" file is separated by new lines and we can utilize this function.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
testFile.txt Contents:
Floppy Jalopy


PHP - File Delete
You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!
Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.
PHP - File Unlink
When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.
If you unlink a file, you are effectively causing the system to forget about it or delete it!
Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.
PHP - Unlink Function
Remember from the PHP File Create lesson that we created a file named testFile.txt.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.
PHP Code:
$myFile = "testFile.txt";
unlink($myFile);
The testFile.txt should now be removed.
PHP - File Append
So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.
PHP - File Open: Append
If we want to add on to a file we need to open it up in append mode. The code below does just that.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2
PHP - Append: Why Use It?
The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

PHP - File Truncate
As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.
PHP - File Open: Truncate
To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
PHP - Truncate: Why Use It?
Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.
For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.
This might not be the most efficient program, but it is a nice usage of truncate.

PHP - File Upload
A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.
PHP - File Upload: HTML Form
Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our HTML Form lesson for a more in-depth look at forms.
HTML Code:


Choose a file to upload:



Here is a brief description of the important parts of the above code:
enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.
action="uploader.php" - The name of our PHP page that will be created, shortly.
method="POST" - Informs the browser that we want to send information to the server using POST.
input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.
Save that form code into a file and call it upload.html. If you view it in a browser it should look like this:
Display:
Choose a file to upload:
After the user clicks submit, the data will be posted to the server and the user will be redirected to uploader.php. This PHP file is going to process the form data and do all the work.
PHP - File Upload: What's the PHP Going to Do?
Now that we have the right HTML form we can begin to code the PHP script that is going to handle our uploads. Typically, the PHP file should make a key decision with all uploads: keep the file or throw it away. A file might be thrown away from many reasons, including:
The file is too large and you do not want to have it on your server.
You wanted the person to upload a picture and they uploaded something else, like an executable file (.exe).
There were problems uploading the file and so you can't keep it.
This example is very simple and omits the code that would add such functionality.
PHP - File Upload: uploader.php
When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.
The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.
uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
$_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file.
$_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.
Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.
PHP Code:
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$_FILES['uploadedfile']['tmp_name'];
NOTE: You will need to create a new directory in the directory where uploader.php resides, called "uploads", as we are going to be saving files there.
We now have all we need to successfully save our file to the server. $target_path contains the path where we want to save our file to.
PHP - File Upload: move_uploaded_file Function
Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path where it is to be moved to (check!).
PHP Code:
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
If the upload is successful, then you will see the text "The file filename has been uploaded". This is because $move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try again!" would be displayed.

PHP Functions

PHP - Functions
A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!
For example, you might have a company motto that you have to display at least once on every webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this sounds like a situation where I might need functions."
Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't give up if you functions confuse you at first!
Creating Your First PHP Function
When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function name that you will be able to call upon your function, so make it easy to type and understand.
The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First, you must tell PHP that you want to create a function. You do this by typing the keyword function followed by your function name and some other stuff (which we'll talk about later).
Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for myCompanyMotto.
PHP Code:
function myCompanyMotto(){
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
With a properly formatted function in place, we can now fill in the code that we want our function to execute. Do you see the curly braces in the above example "{ }"? These braces define where our function's code goes. The opening curly brace "{" tells php that the function's code is starting and a closing curly brace "}" tells PHP that our function is done!
We want our function to print out the company motto each time it's called, so that sounds like it's a job for the echo function!
PHP Code:
function myCompanyMotto(){
echo "We deliver quantity, not quality!
";
}
?>
That's it! You have written your first PHP function from scratch! Notice that the code that appears within a function is just the same as any other PHP code.
Using Your PHP Function
Now that you have completed coding your PHP function, it's time to put it through a test run. Below is a simple PHP script. Let's do two things: add the function code to it and use the function twice.
PHP Code:
echo "Welcome to Tizag.com
";
echo "Well, thanks for stopping by!
";
echo "and remember...
";
?>
PHP Code with Function:
function myCompanyMotto(){
echo "We deliver quantity, not quality!
";
}
echo "Welcome to Tizag.com
";
myCompanyMotto();
echo "Well, thanks for stopping by!
";
echo "and remember...
";
myCompanyMotto();
?>
Display:
Welcome to Tizag.com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember...
We deliver quantity, not quality!
Although this was a simple example, it's important to understand that there is a lot going on and there are a lot of areas to make errors. When you are creating a function, follow these simple guidelines:
Always start your function with the keyword function
Remember that your function's code must be between the "{" and the "}"
When you are using your function, be sure you spell the function name correctly
Don't give up!
PHP Functions - Parameters
Another useful thing about functions is that you can send them information that the function can then use. Our first function myCompanyMotto isn't all that useful because all it does, and ever will do, is print out a single, unchanging string.
However, if we were to use parameters, then we would be able to add some extra functionality! A parameter appears with the parentheses "( )" and looks just like a normal PHP variable. Let's create a new function that creates a custom greeting based off of a person's name.
Our parameter will be the person's name and our function will concatenate this name onto a greeting string. Here's what the code would look like.
PHP Code with Function:
function myGreeting($firstName){
echo "Hello there ". $firstName . "!
";
}
?>
When we use our myGreeting function we have to send it a string containing someone's name, otherwise it will break. When you add parameters, you also add more responsibility to you, the programmer! Let's call our new function a few times with some common first names.
PHP Code:
function myGreeting($firstName){
echo "Hello there ". $firstName . "!
";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>
Display:
Hello there Jack!
Hello there Ahmed!
Hello there Julie!
Hello there Charles!
It is also possible to have multiple parameters in a function. To separate multiple parameters PHP uses a comma ",". Let's modify our function to also include last names.
PHP Code:
function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!
";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>
Display:
Hello there Jack Black!
Hello there Ahmed Zewail!
Hello there Julie Roberts!
Hello there Charles Schwab!
PHP Functions - Returning Values
Besides being able to pass functions information, you can also have them return a value. However, a function can only return one thing, although that thing can be any integer, float, array, string, etc. that you choose!
How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function. Something like:
$myVar = somefunction();
Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers.
PHP Code:
function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."
";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."
";
?>
Display:
Before the function, myNumber = 0
After the function, myNumber = 7

PHP - Arrays
An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP's arrays are actually maps (each key is mapped to a value).
PHP - A Numerically Indexed Array
If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this?
It wouldn't make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.
PHP Code:
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare";
In the above example we made use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the employees. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is:
$array[key] = value;
If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.
PHP Code:
echo "Two of my employees are "
. $employee_array[0] . " & " . $employee_array[1];
echo "
Two more employees of mine are "
. $employee_array[2] . " & " . $employee_array[3];
Display:
Two of my employees are Bob & Sally
Two more employees of mine are Charlie & Clare
PHP arrays are quite useful when used in conjunction with loops, which we will talk about in a later lesson. Above we showed an example of an array that made use of integers for the keys (a numerically indexed array). However, you can also specify a string as the key, which is referred to as an associative array.
PHP - Associative Arrays
In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
PHP Code:
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;

echo "Bob is being paid - $" . $salaries["Bob"] . "
";
echo "Sally is being paid - $" . $salaries["Sally"] . "
";
echo "Charlie is being paid - $" . $salaries["Charlie"] . "
";
echo "Clare is being paid - $" . $salaries["Clare"];
Display:
Bob is being paid - $2000
Sally is being paid - $4000
Charlie is being paid - $600
Clare is being paid - $0

PHP - While Loop
Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelopes, and going to work are all examples of tasks that are repeated. The nice thing about programming is that you can avoid such repetitive tasks with a little bit of extra thinking. Most often these repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over again until the task has been completed. Before we show a real example of when you might need one, let's go over the structure of the PHP while loop.
Simple While Loop Example
The function of the while loop is to do a task over and over as long as the specified conditional statement is true. This logical check is the same as the one that appears in a PHP if statement to determine if it is true or false. Here is the basic structure of a PHP while loop:
Pseudo PHP Code:
while ( conditional statement is true){
//do this code;
}
This isn't valid PHP code, but it displays how the while loop is structured. Here is the break down of how a while loop functions when your script is executing:
1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.
2. The code within the while loop is executed.
3. The process starts again at (1). Effectively "looping" back.
4. If the conditional statement is false, then the code within is not executed and there is no more looping. The code following the while loop is then executed like normal.
A Real While Loop Example
Imagine that you are running an art supply store. You would like to print out the price chart for number of brushes and total cost. You sell brushes at a flat rate, but would like to display how much different quantities would cost. This will save your customers from having to do the mental math themselves.
You know that a while loop would be perfect for this repetitive and boring task. Here is how to go about doing it.
Pseudo PHP Code:
$brush_price = 5;
$counter = 10;

echo "";
echo "";
echo "";
while ( $counter <= 100 ) {
echo "";
$counter = $counter + 10;
}
echo "
QuantityPrice
";
echo $counter;
echo "
";
echo $brush_price * $counter;
echo "
";
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500
PHP - For Loop
The for loop is simply a while loop with a bit more code added to it. The common tasks that are covered by a for loop are:
1. Set a counter variable to some initial value.
2. Check to see if the conditional statement is true.
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop.
The for loop allows you to define these steps in one easy line of code. It may seem to have a strange form, so pay close attention to the syntax used!
For Loop Example
Let us take the example from the while loop lesson and see how it could be done in a for loop. The basic structure of the for loop is as follows:
Pseudo PHP Code:
for ( initialize a counter; conditional statement; increment a counter){
do this code;
}
Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated by a semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is needed because these are separate expressions. However, notice that a semicolon is not needed after the "increment counter" expression.
Here is the example of the brush prices done with a for loop .
PHP Code:
$brush_price = 5;

echo "";
echo "";
echo "";
for ( $counter = 10; $counter <= 100; $counter += 10) {
echo "";
}
echo "
QuantityPrice
";
echo $counter;
echo "
";
echo $brush_price * $counter;
echo "
";
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500
PHP For Each Loop
Imagine that you have an associative array that you want to iterate through. PHP provides an easy way to use every element of an array with the Foreach statement.
In plain english this statement will do the following:
For each item in the specified array execute this code.
While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.
PHP For Each: Example
We have an associative array that stores the names of people in our company as the keys with the values being their age. We want to know how old everyone is at work so we use a Foreach loop to print out everyone's name and age.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){
echo "Name: $key, Age: $value
";
}
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34
The syntax of the foreach statement is a little strange, so let's talk about it some.
Foreach Syntax: $something as $key => $value
This crazy statement roughly translates into: For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value.
The operator "=>" represents the relationship between a key and value. You can imagine that the key points => to the value. In our example we named the key $key and the value $value. However, it might be easier to think of it as $name and $age. Below our example does this and notice how the output is identical because we only changed the variable names that refer to the keys and values.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $name => $age){
echo "Name: $name, Age: $age
";
}
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

PHP - Do While Loop
A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous lessons on While Loops the conditional statement is checked comes back true then the code within the while loop is executed. If the conditional statement is false then the code within the loop is not executed.
On the other hand, a do-while loop always executes its block of code at least once. This is because the conditional statement is not checked until after the contained code has been executed.
PHP - While Loop and Do While Loop Contrast
A simple example that illustrates the difference between these two loop types is a conditional statement that is always false. First the while loop:
PHP Code:
$cookies = 0;
while($cookies > 1){
echo "Mmmmm...I love cookies! *munch munch munch*";
}
Display:

As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the code within the while loop was not executed. Now, can you guess what will happen with a do-while loop?
PHP Code:
$cookies = 0;
do {
echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);
Display:
Mmmmm...I love cookies! *munch munch munch*