Saturday, February 28, 2009

IMAGE tag

The tag embeds an image in an HTML page.

The tag has two required attributes: src and alt.
The Image Tag and the Src Attribute

In HTML, images are defined with the tag.

The tag is empty, which means that it contains attributes only and it has no closing tag.

To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute is the URL of the image you want to display on your page.

The syntax of defining an image:



The URL points to the location where the image is stored. An image named "boat.gif" located in the directory "images" on "www.w3schools.com" has the URL: http://www.w3schools.com/images/boat.gif.

The browser puts the image where the image tag occurs in the document. If you put an image tag between two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph.
The Alt Attribute

The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is an author-defined text:

Big Boat

The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load images. The browser will then display the alternate text instead of the image. It is a good practice to include the "alt" attribute for each image on a page, to improve the display and usefulness of your document for people who have text-only browsers.
Basic Notes - Useful Tips

If an HTML file contains ten images - eleven files are required to display the page right. Loading images take time, so my best advice is: Use images carefully.

ANCHOR tag

Links on web pages are created using the anchor tags. These links can point to a different document
on the Internet or to some anchor on the same page. Documents linked in this manner need not be HTML (or PHP/ASP) files. You can place a link to any kind of file.

Anchor Tag attributes
charset= text
Character encoding which specifies the character encoding of the target URL.
Example: charset=utf-8
href = relative address (i.e. the address of a file RELATIVE to the current document)
move up to next higher folder using ../
move down to a lower folder using folder (or 'directory' on the server) name
display from fragmentation-id position on document using #fragmentation-id.
Example-1: - current document displayed with fragmentation-id section at top of display. This is coding for moving round the same document, perhaps with an index at the top linking to sub-sections lower down.
Example-2: - file in current folder displayed with top of page at top of display. With no fragmentation id specified, the display is from the top of the page.
Example-3: - file in next highest folder is displayed with the top of the page at the top of the display.
Example-4: - a file in a lower folder is displayed with fragmentation-id at the top of the display.
href = absolute address
Example-5: - the server default file in directory at this absolute address is displayed from top of page.
Example-6: - specified file at this absolute address is displayed from top of page.
Example-7: - file with this absolute address is displayed from fragmentation-id position.
Example-8: - file (schedule.htm) with absolute address (http://www.bbc.com/radio4/) - is displayed from fragmentation-id position (#today) , and gives a fragmentation-id (refbbc) for the current position in the current document.

types of file
Normally the link is to another webpage (with file extension htm or html), but links to other file extensions are possible. An extensive variety of files can be accommodated, but the presumption is that the user has associated the file extension with a suitable application program, for example:
.doc associated with MS Word. .pdf associated with Adobe Reader. .ppt associated with MS Powerpoint.
Formats may include .wav for audio, .pdf / .doc for desktop publishing, .ppt for presentation, .exl for spreadsheet, etc. Consequently, only the most popular, legacy formats should be linked, in order to ensure that the majority of users' set-ups can deal with the format presented.
Note 1: A file-type icon is often added to the link for visual confirmation of a non-HTML link -
word minutes.doc estimates.exl excel
adobe acrobat instructions.pdf presentation.ppt adobe acrobat
Note 2: A link to a PDF format document is often accompanied by
adobe reader Link to Adobe Reader download
providing the user with a link to downloadable software, which can be used to view the file.

href = mailto (i.e. to send an e-mail)
Example: e-mail
Note 1: Minimise spam, frustrate the spambots by using coding to hide the e-mail address.
Note 2 : Make it clear that it is an e-mail link.
name= text
Example: - signifies a Fragmentation Identifier (anchor) position on the current document.
Note: a linking href must use a leading # after the document name (see Examples - 1,4,7,8)
further Fragmentation Identifier
The id attribute in the start tag of A (and other elements) identifies a reference position in the document. Name (or id) must be unique for the document. When linked using the fragmentation identifier, the browser shows the start of the fragment at the top of the display.
id=text
Example:

- signifies a fragmentation identifier position on the page.
Note: the linking href must use a leading # after the document name (see Examples - 1,4,7,8)
rel= text
Specifies the relationship between the current document and the target URL.
Example: rel=index
Options: alternate,designates,stylesheet,start,next,prev,contents,index,glossary,copyright, chapter,section,subsection,appendix,help,bookmark
rev= text
Specifies the reverse relationship between the document and the target URL
Example: rel=subsection
Options: alternate,designates,stylesheet,start,next,prev,contents,index,glossary, copyright,chapter,section,subsection,appendix,help,bookmark
target= text
Example: target="_blank" - retains 'stickability' and hence generally preferable.
Options: a href="URL" target="_blank" creates a new window of default size
a href="URL" target="_parent" targets the frameset in which the current page belongs
a href="URL" target="_self" targets the current window
a href="URL" target="_top" targets the main browser window, eliminating all frames
title= text
The text displayed when the mouse hovers over the text-link (mouse-over tool-tip).
Note: In the case of a graphic link (depending on the browser), the ALT attribute of the IMG tag may take precedence.
Example: title="Tool Tip displayed on hover" - when the mouse hovers over the link, a tool tip is displayed.

Mouseover Tool Tip

* an exciting description can encourage the user to investigate the link
* use to give extra information

Anchor Tag hypertext link
hypertext as text
Example: Anchor tag definition - SEs use linking text as keywords to categorise the content of the link. Decide which are the most appropriate keywords for the content and use them in the link text.

Link-text content

* One way to improve your Search Engine ranking.
* Carefully select appropriate, hypertext keywords within the website.
* Ask external link creators to use your own, selected, keyword-rich anchor-text in their external hypertext link.

Link-text appearance

* length can be controlled by incorporating the line return character
* change font characteristics using CSS (see below)

hypertext as graphic
Note 1: Always specify IMG attributes width, height, alt, border.
Note 2: According to the browser, with the Tool Tip the IMG, alt attribute may take priority over the A, title attribute.
Homepage Example: Homepage
- image is bordered by the link colour if border=0 is omitted.
Homepage Example: Homepage
- use border=0 to eliminate link-colour border to graphic.
Homepage
Home
Example: Homepage
Home

- a combination of graphic and text is often used to clearly identify the hyperlink.


Client-side mapping
By moving the cursor to different parts of the graphic, different links can be created.
See the IMG tag attribute usemap for further information.

Web link legacy and consistency
In the early days of the WWW, links were all coloured blue and underlined. Users still expect text of this colour to operate as a link, so to meet their expectations and to give them confidence when using the site, it is recommended that link text throughout the site is generally coloured blue.
Such a global feature should be coded in a Linked CSS stylesheet.

Dynamic link - styled attributes
To attract the user's attention, and to confirm that a hyperlink exists, it is always good policy to make the hypertext dynamic.
These sort of changes are particularly powerful for the navigation components, which could involve contrasts of the 'a hover' and 'a' css properties and values. However dynamic changes which could drastically affect nearby text and alter the layout (e.g. font-size) are not recommended.
Example:
Homepage
Home The style attributes for the link text and graphic can be selected so that a mouseover produces a dynamic change of appearance.
This graphic has a transparent background, with the 'white' background-color showing through.
On 'hover' the background-color changes from 'white' to 'purple' with the link-text font-color changing from 'blue' to 'orange'.
Note: IE produces the expected result, Firefox makes transparent only the lower half of the graphic.
Linked CSS style sheet Pseudo-class selectors
Currently these are: hover, active, link, visited, lang, focus
The first four are directly relevant to an anchor tag link.
A linked style sheet contains declarations of global properties and values.
Example:
a:link {color:#0000CC; text-decoration:none; font-weight: bold; }
a:active {color:#FF0000; text-decoration:none; }
a:visited {color:#660099; text-decoration:none; font-weight: bold; }
a:hover {color:#FF9900; text-decoration:none; background-color: white; }
Note: use of the COLON rather than the usual full stop.

Varied CSS link tags
In general, it is very confusing for the user if the link tags vary throughout the website, but in exceptional cases this may be required.
On a linked style sheet an alternative set of parameters could be defined for the anchor attributes.
Example:
a.exc:link {color:#0000CC; text-decoration:none; font-weight: bold; }
a.exc:active {color:#FF0000; text-decoration:none; }
a.exc:visited {color:#660099; text-decoration:none; font-weight: bold; }
a.exc:hover {color:#FF9900; text-decoration:none; background-color: purple; }
Notes:

* See above example in 'Dynamic link - styled attributes'. On 'hover' the background-color is 'purple' rather than the usual 'white', making 'hover' dynamic - on a white, transparent-background, graphical link.
* Coded using the class="exc" notation.
e.g.

Use CSS to change link characteristics
On rare occasions, it may be necessary to change locally, the global characteristics inherited from the linked stylesheet.

Change the static anchor-text attributes
The anchor-text can be changed within the anchor coding using CSS attributes.
This could involve:
color style="color:red;" font color
font-family style="font-family: times new roman;" font-family
font-weight style="font-weight: bold;" bold
font-style style="font-style: italic;" italic
font-size style="font-size: x-small;" x-small
text-decoration style="text-decoration: underline;" underline
background-color style="background-color: #ffccff;"

MAP tag

The maptag is used to define a client-side image-map. An image-map is an image with clickable areas.

The name attribute is required in the map element. This attribute is associated with the 's usemap attribute and creates a relationship between the image and the map.

The map element contains a number of area elements, that defines the clickable areas in the image map.
Required Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.
Attribute Value Description DTD
name mapname Specifies the name for an image-map STF

Standard Attributes
id, class, title, style, dir, lang, xml:lang, tabindex, accesskey

For a full description, go to Standard Attributes.

Event Attributes
onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup, onfocus, onblur

For a full description, go to Event Attributes.

AREA TAG

Das -Tag wird zusammen mit dem map-Tag benutzt, um eine clientseitige Image Map zu erzeugen, die in verschiedene maus-sensitive Bereiche (auch »Hot Spots« genannt) unterteilt ist. Wenn die Maus einen Bereich der Map anklickt, kann ein Attribut im -Tag direkt eine Aktion einleiten – z.B. kann in jedem Bereich ein Link durch ein href-Attribut erzeugt werden. Da der Bereich maus-sensitiv ist, kann auch das Hovern mit der Maus als Ereignis erkannt werden.

Das -Tag muss im MAP-Element enthalten sein. Das IMG-Element kann vor oder nach dem map-Tag, in dem die -Tags enthalten sind, stehen.

Für das -Tag können keine CSS-Eigenschaften notiert werden – AREA-Elemente sind nur maus-sensitive Bereiche, aber bilden keine Blöcke im Dokument.

Attribute für area

accesskey
bestimmt eine Taste auf der Tastatur, die beim Drücken zusammen mit der Alt-, Strg- oder Befehlstaste einen Link aktiviert.
alt
verknüpft einen Text mit einem individuellen Bereich der Map. Wenn die Maus über den Bereich fährt, stellt ein kleines Fenster diesen Text dar.
coords
legt die (x,y)-Koordinaten für jede Form in der Image Map fest. Die Koordinaten sind der x- und y-Abstand von der oberen linken Ecke (0,0) zum Bild. Die Anzahl der Koordinaten hängt von der Form ab, die im shape-Attribut definiert wird.
rect: top left bottom right
circle: center radius, wobei center als x,y-Paar angegeben wird
poly: Ecken des Polygons.
href
URL-Adresse eines Links. Jedes -Tag im Bild kann einen Link enthalten.
nohref
gibt an, dass der im -Tag definierte Bereich kein Link ist. Dann zeigen die Browser den Hot Spot der Image Map beim Hovern mit der Maus auch nicht mit einem entsprechenden Cursor und der Cursor kann auch nicht durch ein Stylesheet geändert werden.
shape
definiert die geometrische From der Image Map. Das kann entweder ein Kreis (circle oder circ), ein Polygon (polygon oder poly) oder ein Viereck (rectangle oder rect) sein.
tabindex
ganze Zahl, die den Rang innerhalb der Tabulatoraufrufe bei der Navigation mit der Tastatur festlegt.

TABLE TAG

Tables are defined with the table tag. A table is divided into rows (with the tag), and each row is divided into data cells (with the tag). The letters td stands for "table data," which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.










row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2


How it looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

Tables and the Border Attribute

If you do not specify a border attribute the table will be displayed without any borders. Sometimes this can be useful, but most of the time, you want the borders to show.

To display a table with borders, you will have to use the border attribute:






Row 1, cell 1Row 1, cell 2



Headings in a Table

Headings in a table are defined with the tag.














HeadingAnother Heading
row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2


How it looks in a browser:
Heading Another Heading
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

Empty Cells in a Table

Table cells with no content are not displayed very well in most browsers.










row 1, cell 1row 1, cell 2
row 2, cell 1


How it looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1

Note that the borders around the empty table cell are missing (NB! Mozilla Firefox displays the border).

To avoid this, add a non-breaking space ( ) to empty data cells, to make the borders visible:










row 1, cell 1row 1, cell 2
row 2, cell 1 


How it looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1

Thursday, February 19, 2009

TR tag

Description

Defines a row in a table. It is used within the TABLE tag. The TD tag is used within it to define a cell.
Attributes
ALIGN

Aligns the text for the cells in the row - set to either 'left', 'center', 'justify' or 'right'.
BACKGROUND

Sets the background picture for the cells in the row. To show to an image on the same site use the local path e.g. src="button.gif" or src="folder/photo1.jpg". You can also use dots to link to an image in the parent folder e.g. src="..\diagram.png".
BGCOLOR

Specifies the background colour of the cells in the row. If the BACKGROUND attribute is also used, the image will cover the background colour unless the background image contains transparent areas.

Colours can be defined in this format: #RRGGBB where the values are in hexadecimal format. E.g. #FF0000 is red. Colours can also be defined with words e.g. red.
VALIGN

Vertically aligns the text for the cells in the row - set to either 'baseline', 'bottom', 'middle' or 'top'.

TH tag

The tag is used to create a header cell for the cells in a row in a table element. The purpose of the header is to provide a caption, name, or information about the column of cells. The header text will be displayed in a bold font style.

The td tag is used to create cells that contain the data, information, or text that you wish to display in the table.

The closing tag is optional. However, it is recommended that it always be included.

The coding sequence is:
place header here

Core attributes:

class dir id lang onclick ondblclick onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup style title

Attributes


abbr
The abbr attribute is not recognized by most browsers. You use it to provide an abbreviated summary of the header text.

align
The align attribute is used to set the horizontal alignment of the cell contents. The possible values are center, char, justify, left, and right.

axis
The axis attribute is not recognized by most browsers. This attribute is used to create a list of category names which form the basis of a query. This query is executed against the cells that form the table.

bgcolor
The bgcolor attribute is deprecated effective with version 4.0. You are now to use style sheets. This attribute is used to set the background color for the cell. It can be either a named color (such as red) or a six character hexadecimal RGB color code (such as #e26fa9). This value overrides any color value that was set in the table or tr tags.

char
The char attribute permits you to select a character that will be used to align the contents of the cell. This was designed to allow the decimal points in a column of numbers to be in vertical alignment. The default value is country dependent. In the U.S., it is the first occurrence of a period or a decimal point.

charoff
The charoff attribute is an integer used to specify if the value designated in the char attribute is to be the first, second, or whatever occurrence.

colspan
The colspan attribute allows a header to span horizontally two or more columns (cells). This may be combined with the rowspan attribute to form data cells that encompass several rows and columns.

headers
The headers attribute is not recognized by most browsers. The value of this attribute is a list of cell header names. The names are the values of the cells' id attributes. This attribute is used with speech capable browsers.

height
The height attribute is deprecated effective with version 4.0. You are now to use style sheets. You use this attribute to set a minimum height for the cell. This value is an integer number of pixels. However, you may exceed this minimum height to accommodate the cell contents. The tallest cell in the row determines the actual maximum height which will be adopted by all of the cells in that row.

nowrap
The nowrap attribute is deprecated effective with version 4.0. You are now to use style sheets. You use this attribute to stop word wrapping and display the cell contents in one continuous line. However, you can insert br and p tags to create line and paragraph breaks.

rowspan
The rowspan attribute allows a cell to extend down two or more rows. This may be combined with the colspan attribute to form data cells that encompass several rows and columns.

scope
The scope attribute is not recognized by most browsers. It is used to assign a set of data cells to one header cell. The four possible values are col, colgroup, row, and rowgroup.

valign
The valign attribute is used to set the vertical alignment of the cell contents. The possible values are baseline, bottom, middle, and top.

width
The width attribute is deprecated effective with version 4.0. You are now to use style sheets. It is used to set the horizontal width of the cell. This value is an integer number of pixels. The widest cell sets the width for the entire column.

TD tag

The tag is used to create cells that contain the data, information, or text that you wish to display in the table. You may place as many data cells in a row as you desire.

The th tag is used to create a header cell for the cells in a row in a table element.

The ending tag is optional. However, it is recommended that it be included.

The coding sequence is:
place data here

Core Attributes

class dir id lang onclick ondblclick onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup style title

Attributes


abbr
The abbr attribute is not recognized by most browsers. You use it to provide an abbreviated summary of the data cell text.

align
The align attribute is used to set the horizontal alignment of the cell contents. The possible values are center, char, justify, left, and right.

axis
The axis attribute is not recognized by most browsers. This attribute is used to create a list of category names which form the basis of a query. This query is executed against the cells that form the table.

bgcolor
The bgcolor attribute is deprecated effective with version 4.0. You are now to use style sheets. This attribute is used to set the background color for the cell. It can be either a named color (such as red) or a six character hexadecimal RGB color code (such as #e26fa9). This value overrides any color value that was set in the table or tr tags.

char
The char attribute permits you to select a character that will be used to align the contents of the cell. This was designed to allow the decimal points in a column of numbers to be in vertical alignment. The default value is country dependent. In the U.S., it is the first occurrence of a period or a decimal point.

charoff
The charoff attribute is an integer used to specify if the value designated in the char attribute is to be the first, second, or whatever occurrence.

colspan
The colspan attribute allows a header to span horizontally two or more columns (cells). This may be combined with the rowspan attribute to form data cells that encompass several rows and columns.

headers
The headers attribute is not recognized by most browsers. The value of this attribute is a list of cell names. The names are the values of the cells' id attributes. This attribute is used with speech capable browsers.

height
The height attribute is deprecated effective with version 4.0. You are now to use style sheets. You use this attribute to set a minimum height for the cell. This value is an integer number of pixels. However, you may exceed this minimum height to accommodate the cell contents. The tallest cell in the row determines the actual maximum height which will be adopted by all of the cells in that row.

nowrap
The nowrap attribute is deprecated effective with version 4.0. You are now to use style sheets. You use this attribute to stop word wrapping and display the cell contents in one continuous line. However, you can insert br and p tags to create line and paragraph breaks.

rowspan
The rowspan attribute allows a cell to extend down two or more rows. This may be combined with the colspan attribute to form data cells that encompass several rows and columns.

scope
The scope attribute is not recognized by most browsers. It is used to assign a set of data cells to one header cell. The four possible values are col, colgroup, row, and rowgroup.

valign
The valign attribute is used to set the vertical alignment of the cell contents. The possible values are baseline, bottom, middle, and top.

width
The width attribute is deprecated effective with version 4.0. You are now to use style sheets. It is used to set the horizontal width of the cell. This value is an integer number of pixels. The widest cell sets the width for the entire column.

Forms

Forms are the most popular way to make web pages interactive. Like forms on paper, a form on a web page allows the user to enter requested information and submit it for processing. (Fortunately, forms on a web page are processed much faster.)

The following pages provide a beginning tutorial in how to put forms on your web page, how to include scripts, and some other common forms concepts.

FORM tag

Available in versions: 2.0, 3.2, 4.0
Browser compatibility: Explorer 4, 5 Netscape 4, 6

The form tag is used to delimit the start and stop of a form element and serves as a container for form controls (fields). Control is a technical term which refers to the various elements that can be used inside a form to gather information. The information gathered is referred to as the contents or parameters of the form and is a collection of name/value pairs.

The four tags that can be used to build a form are:

button, input, select, textarea,

The general concept is that the user fills out the appropriate sections of the form as a response to a request for information (such as a shipping address). The user then clicks the submit button. The contents of the form are then submitted for processing, usually to another page on the web site. However, you can also submit to the same page, or to a window or frame.

This ability to use a web site to display products and information, to gather a response via a form from a user, to store and manipulate the gathered information, and then to have the web site respond dynamically to the user input, is the heart of the e-commerce/e-business industry.

There are two required attributes for the form tag. The action attribute dictates where the form contents will be submitted. The method attribute specifies how to send the submission.

It is recommended that you should only place one form per page. It may prove best to divide a long form between two or more pages.

A form element should not contain other form tags. The closing tag is mandatory.

Core Attributes

class dir id lang onclick ondblclick onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup style title

Attributes

accept
The accept attribute is a comma-separated list of file types that can be accepted by the server when using the type="file" content.

accept-charset
The accept-charset attribute is a comma-separated or space-separated list of the character types that the server must be able to support (process) when the contents of a form are submitted.

action
The action attribute sets the URL of the page that the contents (name/value pairs) of the form will be submitted to for processing.

enctype
The enctype attribute specifies the MIME type used to encode the contents of a form. The default is application/x-www-form-urlencoded. When using type="file" content, this attribute must be set to multipart/form-data.

method

The method attribute specifies which of two permitted HTTP methods will be used to pass the contents of a form. The more commonly used post method submits the contents of the form in a two step procedure. First the URL specified by the action attribute is contacted. Second, if the contact is successful, the contents are transmitted to the URL. The get method appends the contents to the end of the URL specified by the action attribute. (A question mark is used to delimit the end of the URL and the start of the contents.)

name
The name attribute is a string of characters that is used to label a form control (field) with a name. The name must be unique to that document and cannot be reused.

onreset
The onreset attribute is an event that allows the execution of JavaScript code when the user resets (clears) the form.

onsubmit
The onsubmit attribute is an event that allows the execution of JavaScript code when the user submits the form. For example, you could call a JavaScript function that performs client-side form verification to ensure that the form is filled out correctly (see code example).

target
The target attribute is used to submit the contents of the form to a specified window or frame.

Here is a sample form that includes client-side verification of fields.

INPUT tag

Available in versions: 2.0, 3.2, 4.0
Browser compatibility: Explorer 4, 5 Netscape 4, 6

The tag is used to create individual form controls (fields). Control is a technical term that refers to the various elements (buttons, check boxes, radio buttons, text areas) that can be used inside a form to gather information.

The four tags that can be used to build a form are:

button, input, select, textarea

The form is the heart of an e-commerce page and the input tag is the heart of a form. There are ten types of form controls that can be created using the input tag. Appropriately, you must use the type attribute to determine the specific type of the control (field). The types are:

button
checkbox
file
hidden
image
password
radio
reset
submit
text


Any number of input tags can be placed anywhere between a pair of opening and closing form tags to create the desired appearance of the form.

There is no closing tag.

Core Attributes

class dir id lang onclick ondblclick onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup style title

Attributes

accept
The accept attribute is used with the type="file" control to specify what kind of files (including the path) that can be attached to the form. It is a comma-delimited list. For example: accept="images/*.gif"

accesskey
The accesskey attribute allows you to designate a key on the keyboard that when pressed, along with the alt or meta key, will bring focus to the input form element. This attribute is poorly supported.

align deprecated 4.0
The align attribute is used with a type="image" control to place the image with respect to any surrounding text. The permitted values are bottom, left. middle, right, and top. This attribute is deprecated effective with version 4.0. However, most browsers continue to recognize this attribute. You are now to use style sheets.

alt
The alt attribute displays an alternative text for browsers that cannot display an image.

checked
The checked attribute is a Boolean value that, if present, allows a checkbox or radio button to be preselected (and have a preselected value).

disabled
The disabled attribute is a Boolean value that, if present, prevents the form control (field) from functioning. In some browsers, the control (field) will appear to be greyed out.

ismap
The ismap attribute is a Boolean value that, when present, signifies that the image is being used as a mouse-clickable server-side image map.

maxlength
The maxlength attribute sets the maximum number of characters that can be entered into a one line text window.

name
The name attribute is a string of characters that is used to label a form control (field) with a name. The name must be unique to that document and cannot be reused.

onblur
The onblur attribute is an event that allows the execution of JavaScript code when an element loses focus (for example, the mouse was clicked onto another element or a tab navigation directed the cursor elsewhere).

onchange
The onchange attribute is an event that allows the execution of JavaScript code when the form control (field) has been changed and loses focus.

onfocus
The onfocus attribute is an event that allows the execution of JavaScript code when an element comes into focus (for example, the mouse was clicked onto the element or a tab navigation brought the cursor to the element).

onselect
The onselect attribute is an event that allows the execution of JavaScript code when the form control (field) gains focus.

readonly
The readonly attribute allows you to display a value in a form control (field) that cannot be changed by the user.

size
The size attribute sets the width of a one line text window by defining how many characters can fit in the window.

src
The src attribute is the URL address or directory/file (path/name) where an image file is being stored.

tabindex
The tabindex attribute specifies an integer that defines the rank in the tabbing order for the specified element when you use the keyboard to navigate (tab through) a page. This attribute is poorly supported.

type
The type attribute determines the specific control.

Note that by using style sheets you can effect the appearance of the various types of controls. However, the exact appearance will be browser dependent.

type="button"
The type="button" control creates a rectangular button that can be clicked when you wish a desired action to occur. For example, you could use buttons to navigate through a recordset data source being displayed on a web page. (See the RDS objects in the ADO Quick Reference.) If you want to reset or submit the form, you should use the type="reset" and type="submit" controls.

A value for the name attribute is required. You can use the value attribute to assign a text that will be displayed on the face of the button. The default color is gray, but that can be changed using style sheets (see example at bottom of page). The text displayed on the button will set the minimum size, but you can set a different size using style sheets or the size attribute.

Frames

Frames allow you to divide the page into several rectangular areas and to display a separate document in each rectangle. Each of those rectangles is called a "frame". Frames are very popular because they are one of the few ways to keep part of the page stationary while other parts change. Frames are also one of the most controversial uses of HTML, because of the way the frames concept was designed, and because many web framed web sites are poorly implemented.

We start off this section with a tutorial on creating frames. We'll start with a simple set of frames, move into more advanced frames pages, and then show some special techniques for using frames.

Frameset tag

The splitting of a browser screen into frames can be done by using Frameset and /Frameset tags.
Attributes of Frameset tag :
Frameset tags require one of the following attributes depending on whether to divide the screen in rows or columns.
Rows: This attribute is used to divide the screen horizontally i.e, into multiple rows. Multiple values can be set to this property depending on the required size of each row. Possible values for this attribute are
Number of pixels or can be expressed as a percentage of the screen resolution
Note: The symbol * indicates the remaining space.

Cols: This attribute is used to divide the screen vertically i.e, into multiple columns. Multiple values can be set to this property depending on the required size of each column. Possible values for this attribute are
Number of pixels or can be expressed as a percentage of the screen resolution
Note: The symbol * indicates the remaining space.

Example:
Frameset rows="30%,30%,*"
... Rest of the definition here ...
/Frameset

Note: There are several advantages(pros) and disadvantages(cons) of using frames. Now you will be eager to see the advantages and disadvantages of frames.

Frame tag

The frame tag is used to load different documents into each unique section that is been defined after the browser screen has been divided into rows and columns using frameset tag.
Note: Frame tag does not have any closing tag.
Attributes of Frame tag :
src: Specifies the url of the document to be loaded into the frame.

MarginWidth: Specifies the amount of space to be left along the sides of the frame.

MarginHeight: Specifies the amount of space to be left at the top and bottom of the frame.

Name: Used to give a unique name for the frame. The name must begin with an alphanumeric character.

NoResize: Disables the resizing capability of the frame.

Scrolling: This is used to decide whether to have scrollbars (Horizontal , Vertical) in a frame. This possibly take 3 values Yes , No or Auto.

Example:
Frameset rows="50%,50%"
Frame src="frame1src.html"
Frame src="frame2src.html"
/Frameset

Wednesday, February 4, 2009

What Is PHP?

The endless possibilities of the PHP scripting language and a great community of users has made it one of the most popular open-source languages. For all you people living outside the UNIX world, Open Source means it doesn't cost anything. You can use it as much as you want and where you want, and nobody will ever charge you thousands of dollars for licenses and support. Even though it was originally conceived as a set of macros to help coders maintain personal home pages, its name grew a lot more from its purpose. Since then, PHP's capabilities have been extended, taking it beyond a set of utilities to a full-featured programming language, capable of managing huge database-driven online environments.

PHP scripting

PHP is now officially known as "PHP: HyperText Preprocessor". It is a server-side scripting language usually written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP binary or module, which is server-side installed. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers - the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user?s web-browser, therefore it can never tell the user whether the web-server uses PHP or not, because all the browser sees is HTML.

PHP's support for Apache and MySQL further increases its popularity. Apache is now the most-used web-server in the world, and PHP can be compiled as an Apache module. MySQL is a powerful free SQL database, and PHP provides a comprehensive set of functions for working with it. The combination of Apache, MySQL and PHP is all but unbeatable.

That doesn?t mean that PHP cannot work in other environments or with other tools. In fact, PHP supports an extensive list of databases and web-servers. The rise in popularity of PHP has coincided with a change of approach in web-publishing. While in the mid-1990s it was ok to build sites, even relatively large sites, with hundreds of individual hard-coded HTML pages, today?s webmasters are making the most of the power of databases to manage their content more effectively and to personalize their sites according to individual user preferences.

Why Use PHP?

If you need to embed dynamic text into static text, you’ll find PHP extremely useful. It was designed for this, and it excels at it. PHP is also very useful for integrating web pages with databases.

The PHP scripting language resembles JavaScript, Java, and Perl, These languages all share a common ancestor, the C programming language.

PHP is most different from JavaScript and Java. PHP is a server-side scripting language. All of the “work” is done on the server. JavaScript (and Java) generally run on the client. They have little access to the information that the server has, and mediated access to information on the client. They can do lots of things on the client that PHP cannot. PHP has full access to the information that the server has, and very little access to information that the client has. In fact, it only has information that the client tells the server and that the server passes on to PHP. Because it is on the server, however, PHP cannot be modified by the client. While you cannot necessarily trust the information that the client gives to PHP, you can trust that your PHP is doing what you told it to do. Because PHP is on the server end, your PHP scripts can affect your server--such as by keeping an activity log or updating a database.

PHP and Perl often work side-by-side. These are both server-side. Where PHP excels at embedding dynamic content, Perl excels at modifying (or “filtering”) streams of text. PHP excels at putting things into documents, and Perl excels at finding things in documents. After you have learned PHP, you may well find Perl useful for many tasks, especially for command-line tasks. PHP has an advantage over Perl on most web sites because PHP is usually loaded as part of the web server. When scripting languages “run”, the system has to first load the “interpreter” and then “compile” the language into code that the machine can understand. When you tell PHP to echo the current time to the web page, the computer needs to have your command translated into numbers that it can understand. Because the PHP interpreter is already loaded as part of the web server’s software, it is always running. This cuts out half of that process. The interpreter is already loaded, and it can go directly to compiling the language into code. When web servers see a request to run a Perl script, they usually have to first load the Perl interpreter. This happens very quickly, but when there are thousands or tens of thousands of requests coming every second, every “very quickly” can add up.

C programs are “pre-compiled”. They cut out both steps in that process: no interpreter is needed because the program is already compiled into code the machine understands. Because of this, however, C programs must be compiled every time you switch to a new machine. If you move to a different host, you will usually have to recompile your C programs. Sometimes you’ll even have to recompile your C programs when your ISP upgrades their server’s system software. And many ISPs do not provide you with a C compiler. You’ll find that PHP is more “portable” than C in this respect: if it works on one server, it will usually work on any other server that has it. Most ISPs that provide server-side scripting provide PHP.

structure of php

print "Hello Web!";
?>

In this simple script you can see some of the most used components of a PHP script. First off, PHP tags are used to separate the actual PHP content from the rest of the file. You can inform the interpreter that you want it to execute your commands by adding a pair of these: standard tags ""; short tags ""; ASP tags "<% %>"; script tags "". The standard and the script tags are guaranteed to work under any configuration, the other two need to be enabled in your "php.ini"

Now that you know how to define a block of PHP code, take a closer look at the code above. The "print" function is used to output data, so anything output by "print()" ends up in the HTML file. Therefore, you can say that a function is a command that performs an action. Usually, you send some data to the function, and the function uses that data to come up with a result. There are a lot functions in PHP, and almost each one performs a different action. Data sent to a function is almost always placed in parentheses after the function name; there are some exceptions where parentheses are optional, and the "print()" function is one of them.

After that first line of code, you can see a semicolon. This semicolon informs the interpreter that you have completed a statement - a statement is to PHP what a sentence is to the English language. It represents an instruction to the interpreter, and some additional data. If PHP doesn't find a semicolon at the end of your statement, then it will continue parsing the file until it finds one, ignoring any white-spaces or empty lines. So, your one statement doesn't necessarily have to use only one line of code. There can be two or more statements on a single line, but, on the other hand, a statement could use two or more lines. PHP also ignores white spaces, so you can have as many blanks as you want between the statements, and between the statements' parameters. You should know that you don't have to use a semicolon with the last statement in your script (just before the closing tag). So the following scripts are equivalent:

print "This is a test" ;
?>



Commenting you PHP code can be very helpful. If some code seems to be very clear at the time of writing, the same code can look like a black hole a few weeks later, when you want to modify it. So adding comments to your code can save you time later on, and make it easier for other people to work with your code. But, wait, what is a comment? A comment is a text in a script that is ignored by the interpreter. So you can write anything you want in it, from copyright notices to detailed information about your code. PHP recognizes a comment by checking out if it contains two forward slashes ("//") or a single hash sign ("#"). The text beginning from either of these marks until the end of the line is ignored. You can also use multi-line comments. They begin with a forward slash followed by an asterisk ("/*") and end with an asterisk followed by a forward slash ("*/"):

/*
This is a demo script.
All it does is output Hello Web! in your browser.
*/

print "Hello Web!"; //outputs a message

//copyright (C) SoftwareProjects.org 2004
?>

The If Statement

The PHP if statement is very similar to other programming languages use of the if statement, but for those who are not familiar with it.


Think about the decisions you make before you go to sleep. If you have something to do the next day, say go to work, school, or an appointment, then you will set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!

This simple kind of if/then statement is very common in every day life and also appears in programming quite often. Whenever you want to make a decision given that something is true (you have something to do tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.


The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.

This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.

If Statement Example

The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.

PHP Code:

$my_name = "someguy";

if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";

Display:
Your name is someguy!
Welcome to my homepage!

Did you get that we were comparing the variable $my_name with "someguy" to see if they were equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if statement turned out to be true, the code segment was executed, printing out "Your name is someguy!". Let's go a bit more in-depth into this example to iron out the details.

* We first set the variable $my_name equal to "someguy".
* We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "someguy"
* The comparison between $my_name and "someguy" was done with a double equal sign "==", not a single equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.
* Translated into english the PHP statement ( $my_name == "someguy" ) is ( $my_name is equal to "someguy" ).
* $my_name is indeed equal to "someguy" so the echo statement is executed.

A False If Statement


Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:

PHP Code:


$my_name = "anotherguy";

if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";

Variables

In this Tutorial you'll learn about Variables and different Data Types in PHP. This includes - what is a variable, naming conventions of a variable in PHP, various data types namely, String, Numeric and Array data types.

What is a Variable?

Variables are nothing but identifiers to the memory location to store data. We can create any number of varibles. In PHP all the variables begin with a dollar sign "$" and the value can be assignes using the "=" operator as shown below:

Example:

$Name, $Name1, $First_Name, $Last_Name

$Name = "David";

$Age = 16;

Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't have to specify the variable type, as it takes the data type of the assigned value. From the above example we understand that '$Name' is of Data type String and '$Age' is of type Numeric.

Limitations in Variable Naming:

PHP has no limit on the length of variable name as in the case of other programming languages. The variable name must start with a letter or underscore. The variable name must be a combination of letters, numbers and underscores. Other characters such as *, +, #, @ are not allowed and causes error if used.

Data Types in PHP

In PHP the data type of a variable is not set by the programmer. PHP decides the data type of variables after interpreting the web page. Data Types in PHP include:

* Numeric data type
* String data type
* Array data type

Numeric data type

Numeric data type is used for number. There are two different numeric data types:

* Integer
* Double

Integer Data Type

Integer data types contain whole number values.

Example:

$intmark = 100;

Doubles

Double contains floating point numbers.

Example:

$doubtotal = 99.5;

String Data Type

String data type is used to contain textual information or letters. The value is assigned within quotes as shown below.

Example:

$strName = "David";

$strId = "David123";

String Concatenation

String Concatenation is a process of adding two strings. This is done by attaching one string to the end of another string. This is done by using '.' (period) operator as shown below:

Example:

$strFirst_Name = "David";

$strSpace = " ";

$strLast_Name = "John";

$strName = $strFirst_Name.$strSpace.$strLast_Name;

echo $strName;

Output:

David John

Array Data Type

Array data type is used to contain many values in a single variable. Each array element can be retrieved by using the array variable name and its key/index value. We can declare an array variable in different ways as shown below:

Example:

$arrMark[0] = 95;

$arrMark[1] = 88;

$arrMark[3] = 77;

(Or)

$arrMark = array(95,88,77);

In the above example, the variable 'arrMark' contains three different values. In the first method the array elements are stored using the key values (0, 1, 2), but in the second example the keyword 'array' is used to assign values to the array variable. By default, array key element starts with 0.

The array elements can be accessed by using their key values. The different marks stored in the array elements can be added together to obtain the total marks as shown below:

Example:

$intTotalMark = $arrMark[0] + $arrMark[1] + $arrMark[2];

echo $intTotalMark;

Output: 260

In the above two examples we have used the key values as numbers, but it not necessary that the key value must be a number, it can also be a string as shown below:

Example:

$arrMark['maths'] = 95;

$arrMark['english'] = 88;

$arrMark['science'] = 77;

$intTotalMark = $arrMark['maths'] + $arrMark['english']+$arrMark['science'];

echo $intTotalMark;

Application Variables in PHP

In July, 2002, I moved the leosolutions.com web site from a Microsoft IIS web server to a Linux server running Apache to reduce the monthly cost of web hosting. After many years of developing in Microsoft Active Server Pages, the conversion from ASP to PHP was surprisingly easy - nearly every statment in ASP has a one-to-one correspondence with its PHP equivalent. However, I encountered one major problem during the conversion process: PHP has no couterpart for application variables in ASP.

Application variables in ASP work very similar to the $_SESSION variable in PHP. However, unlike the $_SESSION variable, application variables are not specific to an individual user; they persist across every user of every page on the web site.

Benefits

The immediate benefits of application variables may not be apparent, but esperienced ASP coders understand their power. Take this one-liner, for example:

You are visitor number

to this web site.

Application variables have many other purposes. On the leosolutions.com web site, I used them primarily to cache common dynamically-generated parts of the page, such as the menu bars and project tab. (Yes, the menu bars on my are dynamically generated from a database) Since this content doesn't change often, it would be a waste of resources (and cause slower response times) to generate these elements on-the-fly, each time a page was requested. Instead, the PHP script checks the application variables for the element. If it is found, the PHP script simply sends the HTML code stored in the application variable directly to the output. Otherwise, the content is generated from the database, and stored to the application variables for future use.

Solution

I looked on the web and read numerous other work-arounds for application variables in PHP, but found none that I liked. Every one required too much overhead code, or else multiple lines of code to actually use the variables. Here is my solution:

app.php


define("APP_DATA_FILE",
"/tmp/application.data");

function application_start ()
{
global $_APP;

// if data file exists, load application
// variables
if (file_exists(APP_DATA_FILE))
{
// read data file
$file = fopen(APP_DATA_FILE, "r");
if ($file)
{
$data = fread($file,
filesize(APP_DATA_FILE));
fclose($file);
}

// build application variables from
// data file
$_APP = unserialize($data);
}
}

function application_end ()
{
global $_APP;

// write application data to file
$data = serialize($_APP);
$file = fopen(APP_DATA_FILE, "w");
if ($file)
{
fwrite($file, $data);
fclose($file);
}
}

?>


Usage

The usage of the $_APP variable is very similar to $_SESSION. Before using it on a page, you must include app.php and call application_start(). When you are finished, you must call application_end().

Sample PHP file using application variables:

include("app.php");
application_start();
?>

< html>
< body>
You are visitor number

to this web site.
< /body>
< /html>

application_end();
?>


Optimizations and Other Notes

Numerous improvements can be made to this code, but they are not included here for simplicity.

* For added security, permissions on the application data file should not allow any user, except for the web server, to read or write to it. Otherwise, if application variables contained sensitive data, such as passwords or credit card information, other users on the system could read this data.
* To keep from writing to disk unnecessarily, only call application_end() if data in the $_APP variable has changed.
* Another alternative is to let the application_end() function determine whether the $_APP variable has been changed, and only write it to disk if necessary. Simply make a copy of the $_APP variable in application_start(), then compare $_APP to the original in application_end().
* Finally, don't forget that unlike $_SESSION, the $_APP variable is only available in the global scope. When using $_APP from inside a function, be sure to include the statement global $_APP; at the top of the function.

Arrays

As we discussed in Chapter 2, PHP supports both scalar and compound data types. In this chapter, we'll discuss one of the compound types: arrays. An array is a collection of data values, organized as an ordered collection of key-value pairs.

This chapter talks about creating an array, adding and removing elements from an array, and looping over the contents of an array. There are many built-in functions that work with arrays in PHP, because arrays are very common and useful. For example, if you want to send email to more than one email address, you'll store the email addresses in an array and then loop through the array, sending the message to the current email address. Also, if you have a form that permits multiple selections, the items the user selected are returned in an array.

Indexed Versus Associative Arrays

There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables. The first column is the key, which is used to access the value.

PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is what the keys happen to be. Some array features are provided mainly for use with indexed arrays, because they assume that you have or want keys that are consecutive integers beginning at 0. In both cases, the keys are unique--that is, you can't have two elements with the same key, regardless of whether the key is a string or an integer.

PHP arrays have an internal order to their elements that is independent of the keys and values, and there are functions that you can use to traverse the arrays based on this internal order. The order is normally that in which values were inserted into the array, but the sorting functions described later let you change the order to one based on keys, values, or anything else you choose.

Identifying Elements of an Array

You can access specific values from an array using the array variable's name, followed by the element's key (sometimes called the index) within square brackets:

$age['Fred']
$shows[2]

The key can be either a string or an integer. String values that are equivalent to integer numbers (without leading zeros) are treated as integers. Thus, $array[3] and $array['3'] reference the same element, but $array['03'] references a different element. Negative numbers are valid keys, and they don't specify positions from the end of the array as they do in Perl.

You don't have to quote single-word strings. For instance, $age['Fred'] is the same as $age[Fred]. However, it's considered good PHP style to always use quotes, because quoteless keys are indistinguishable from constants. When you use a constant as an unquoted index, PHP uses the value of the constant as the index:

define('index',5);
echo $array[index]; // retrieves $array[5], not $array['index'];

You must use quotes if you're using interpolation to build the array index:

$age["Clone$number"]

However, don't quote the key if you're interpolating an array lookup:

// these are wrong
print "Hello, $person['name']";
print "Hello, $person["name"]";
// this is right
print "Hello, $person[name]";

Storing Data in Arrays

Storing a value in an array will create the array if it didn't already exist, but trying to retrieve a value from an array that hasn't been defined yet won't create the array. For example:

// $addresses not defined before this point
echo $addresses[0]; // prints nothing
echo $addresses; // prints nothing
$addresses[0] = 'spam@cyberpromo.net';
echo $addresses; // prints "Array"

Using simple assignment to initialize an array in your program leads to code like this:

$addresses[0] = 'spam@cyberpromo.net';
$addresses[1] = 'abuse@example.com';
$addresses[2] = 'root@example.com';
// ...

That's an indexed array, with integer indexes beginning at 0. Here's an associative array:

$price['Gasket'] = 15.29;
$price['Wheel'] = 75.25;
$price['Tire'] = 50.00;
// ...

An easier way to initialize an array is to use the array( ) construct, which builds an array from its arguments:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
'root@example.com');

To create an associative array with array( ), use the => symbol to separate indexes from values:

$price = array('Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Notice the use of whitespace and alignment. We could have bunched up the code, but it wouldn't have been as easy to read:

$price = array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

To construct an empty array, pass no arguments to array( ):

$addresses = array( );

You can specify an initial key with => and then a list of values. The values are inserted into the array starting with that key, with subsequent values having sequential keys:

$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.

If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. Thus, the following code is probably a mistake:

$whoops = array('Friday' => 'Black', 'Brown', 'Green');
// same as
$whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');

Adding Values to the End of an Array

To insert more values into the end of an existing indexed array, use the [] syntax:

$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'

This construct assumes the array's indexes are numbers and assigns elements into the next available numeric index, starting from 0. Attempting to append to an associative array is almost always a programmer mistake, but PHP will give the new elements numeric indexes without issuing a warning:

$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'

Assigning a Range of Values

The range( ) function creates an array of consecutive integer or character values between the two values you pass to it as arguments. For example:

$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);
$letters = range('a', 'z'); // $numbers holds the alphabet
$reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);

Only the first letter of a string argument is used to build the range:

range('aaa', 'zzz') /// same as range('a','z')

Getting the Size of an Array

The count( ) and sizeof( ) functions are identical in use and effect. They return the number of elements in the array. There is no stylistic preference about which function you use. Here's an example:

$family = array('Fred', 'Wilma', 'Pebbles');
$size = count($family); // $size is 3

These functions do not consult any numeric indexes that might be present:

$confusion = array( 10 => 'ten', 11 => 'eleven', 12 => 'twelve');
$size = count($confusion); // $size is 3

Padding an Array

To create an array initialized to the same value, use array_pad( ). The first argument to array_pad( ) is the array, the second argument is the minimum number of elements you want the array to have, and the third argument is the value to give any elements that are created. The array_pad( ) function returns a new padded array, leaving its argument array alone.

Here's array_pad( ) in action:

$scores = array(5, 10);
$padded = array_pad($scores, 5, 0); // $padded is now array(5, 10, 0, 0, 0)

Notice how the new values are appended to the end of the array. If you want the new values added to the start of the array, use a negative second argument:

$padded = array_pad($scores, -5, 0);

Assign the results of array_pad( ) back to the original array to get the effect of an in situ change:

$scores = array_pad($scores, 5, 0);

If you pad an associative array, existing keys will be preserved. New elements will have numeric keys starting at 0.
Multidimensional Arrays

The values in an array can themselves be arrays. This lets you easily create

multidimensional arrays:

$row_0 = array(1, 2, 3);
$row_1 = array(4, 5, 6);
$row_2 = array(7, 8, 9);
$multi = array($row_0, $row_1, $row_2);

You can refer to elements of multidimensional arrays by appending more []s:

$value = $multi[2][0]; // row 2, column 0. $value = 7

To interpolate a lookup of a multidimensional array, you must enclose the entire array lookup in curly braces:

echo("The value at row 2, column 0 is {$multi[2][0]}\n");

Failing to use the curly braces results in output like this:

The value at row 2, column 0 is Array[0]

Extracting Multiple Values

To copy all of an array's values into variables, use the list( ) construct:

list($variable, ...) = $array;

The array's values are copied into the listed variables, in the array's internal order. By default that's the order in which they were inserted, but the sort functions described later let you change that. Here's an example:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a, $w) = $person; // $n is 'Fred', $a is 35, $w is 'Betty'

If you have more values in the array than in the list( ), the extra values are ignored:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a) = $person; // $n is 'Fred', $a is 35

If you have more values in the list( ) than in the array, the extra values are set to NULL:

$values = array('hello', 'world');
list($a, $b, $c) = $values; // $a is 'hello', $b is 'world', $c is NULL

Two or more consecutive commas in the list( ) skip values in the array:

$values = range('a', 'e');
list($m,,$n,,$o) = $values; // $m is 'a', $n is 'c', $o is 'e'

Slicing an Array

To extract only a subset of the array, use the array_slice( ) function:

$subset = array_slice(array, offset, length);

The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array. The offset parameter identifies the initial element to copy (0 represents the first element in the array), and the length parameter identifies the number of values to copy. The new array has consecutive numeric keys starting at 0. For example:

$people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');
$middle = array_slice($people, 2, 2); // $middle is array('Harriet', 'Brenda')

It is generally only meaningful to use array_slice( ) on indexed arrays (i.e., those with consecutive integer indexes, starting at 0):

// this use of array_slice( ) makes no sense
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
$subset = array_slice($person, 1, 2); // $subset is array(0 => 35, 1 => 'Betty')

Combine array_slice( ) with list( ) to extract only some values to variables:

$order = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');
list($second, $third) = array_slice($order, 1, 2);
// $second is 'Dick', $third is 'Harriet'

Splitting an Array into Chunks

To divide an array into smaller, evenly sized arrays, use the array_chunk( ) function:

$chunks = array_chunk(array, size [, preserve_keys]);

The function returns an array of the smaller arrays. The third argument, preserve_keys, is a Boolean value that determines whether the elements of the new arrays have the same keys as in the original (useful for associative arrays) or new numeric keys starting from 0 (useful for indexed arrays). The default is to assign new keys, as shown here:

$nums = range(1, 7);
$rows = array_chunk($nums, 3);
print_r($rows);
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
)
)

Keys and Values

The array_keys( ) function returns an array consisting of only the keys in the array, in internal order:

$array_of_keys = array_keys(array);

Here's an example:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$keys = array_keys($person); // $keys is array('name', 'age', 'wife')

PHP also provides a (less generally useful) function to retrieve an array of just the values in an array, array_values( ):

$array_of_values = array_values(array);

As with array_keys( ), the values are returned in the array's internal order:

$values = array_values($person); // $values is array('Fred', 35, 'Wilma');

Checking Whether an Element Exists

To see if an element exists in the array, use the array_key_exists( ) function:

if (array_key_exists(key, array)) { ... }

The function returns a Boolean value that indicates whether the second argument is a valid key in the array given as the first argument.

It's not sufficient to simply say:

if ($person['name']) { ... } // this can be misleading

Even if there is an element in the array with the key name, its corresponding value might be false (i.e., 0, NULL, or the empty string). Instead, use array_key_exists( ) as follows:

$person['age'] = 0; // unborn?
if ($person['age']) {
echo "true!\n";
}
if (array_key_exists('age', $person)) {
echo "exists!\n";
}
exists!

In PHP 4.0.6 and earlier versions, the array_key_exists( ) function was called key_exists( ). The original name is still retained as an alias for the new name.

Many people use the isset( ) function instead, which returns true if the element exists and is not NULL:

$a = array(0,NULL,'');
function tf($v) { return $v ? "T" : "F"; }
for ($i=0; $i < removed =" array_splice(array," subjects =" array('physics'," removed =" array_splice($subjects," removed =" array_splice($subjects," new =" array('law'," new =" array('law'," subjects =" array('physics'," new =" array('law'," capitals =" array('USA'"> 'Washington',
'Great Britain' => 'London',
'New Zealand' => 'Wellington',
'Australia' => 'Canberra',
'Italy' => 'Rome');
$down_under = array_splice($capitals, 2, 2); // remove New Zealand and Australia
$france = array('France' => 'Paris');
array_splice($capitals, 1, 0, $france); // insert France between USA and G.B.

Converting Between Arrays and Variables

PHP provides two functions, extract( ) and compact( ), that convert between arrays and variables. The names of the variables correspond to keys in the array, and the values of the variables become the values in the array. For instance, this array:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');

can be converted to, or built from, these variables:

$name = 'Fred';
$age = 35;
$wife = 'Betty';

Creating Variables from an Array

The extract( ) function automatically creates local variables from an array. The indexes of the array elements are the variable names:

extract($person); // $name, $age, and $wife are now set

If a variable created by the extraction has the same name as an existing one, the extracted variable overwrites the existing variable.

You can modify extract( )'s behavior by passing a second argument. Appendix A describes the possible values for this second argument. The most useful value is EXTR_PREFIX_SAME, which says that the third argument to extract( ) is a prefix for the variable names that are created. This helps ensure that you create unique variable names when you use extract( ). It is good PHP style to always use EXTR_PREFIX_SAME, as shown here:

$shape = "round";
$array = array("cover" => "bird", "shape" => "rectangular");
extract($array, EXTR_PREFIX_SAME, "book");
echo "Cover: $book_cover, Book Shape: $book_shape, Shape: $shape";
Cover: bird, Book Shape: rectangular, Shape: round

Creating an Array from Variables

The compact( ) function is the complement of extract( ). Pass it the variable names to compact either as separate parameters or in an array. The compact( ) function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that do not correspond to actual variables are skipped. Here's an example of compact( ) in action:

$color = 'indigo';
$shape = 'curvy';
$floppy = 'none';

$a = compact('color', 'shape', 'floppy');
// or
$names = array('color', 'shape', 'floppy');
$a = compact($names);

Traversing Arrays

The most common task with arrays is to do something with every element--for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you're performing.

The foreach Construct

The most common way to loop over elements of an array is to use the foreach construct:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
foreach ($addresses as $value) {
echo "Processing $value\n";
}
Processing spam@cyberpromo.net
Processing abuse@example.com

PHP executes the body of the loop (the echo statement) once for each element of $addresses in turn, with $value set to the current element. Elements are processed by their internal order.

An alternative form of foreach gives you access to the current key:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
foreach ($person as $k => $v) {
echo "Fred's $k is $v\n";
}
Fred's name is Fred
Fred's age is 35
Fred's wife is Wilma

In this case, the key for each element is placed in $k and the corresponding value is placed in $v.

The foreach construct does not operate on the array itself, but rather on a copy of it. You can insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won't attempt to process the deleted or inserted elements.

The Iterator Functions

Every PHP array keeps track of the current element you're working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The iterator functions are:

current( )
Returns the element currently pointed at by the iterator

reset( )
Moves the iterator to the first element in the array and returns it

next( )
Moves the iterator to the next element in the array and returns it

prev( )
Moves the iterator to the previous element in the array and returns it

end( )
Moves the iterator to the last element in the array and returns it

each( )
Returns the key and value of the current element as an array and moves the iterator to the next element in the array

key( )
Returns the key of the current element

The each( ) function is used to loop over the elements of an array. It processes elements according to their internal order:

reset($addresses);
while (list($key, $value) = each($addresses)) {
echo "$key is $value
\n";
}
0 is spam@cyberpromo.net
1 is abuse@example.com

This approach does not make a copy of the array, as foreach does. This is useful for very large arrays when you want to conserve memory.

The iterator functions are useful when you need to consider some parts of the array separately from others. Example 5-1 shows code that builds a table, treating the first index and value in an associative array as table column headings.

Example 5-1: Building a table with the iterator functions

$ages = array('Person' => 'Age',
'Fred' => 35,
'Barney' => 30,
'Tigger' => 8,
'Pooh' => 40);
// start table and print heading
reset($ages);
list($c1, $c2) = each($ages);
echo("\n");
// print the rest of the values
while (list($c1,$c2) = each($ages)) {
echo("\n");
}
// end the table
echo("
$c1$c2
$c1$c2
");





PersonAge
Fred35
Barney30
Tigger8
Pooh40


Using a for Loop

If you know that you are dealing with an indexed array, where the keys are consecutive integers beginning at 0, you can use a for loop to count through the indexes. The for loop operates on the array itself, not on a copy of the array, and processes elements in key order regardless of their internal order.

Here's how to print an array using for:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
for($i = 0; $i < count($array); $i++) { $value = $addresses[$i]; echo "$value\n"; } spam@cyberpromo.net abuse@example.com

Calling a Function for Each Array Element
PHP provides a mechanism, array_walk( ), for calling a user-defined function once per element in an array: array_walk(array, function_name); The function you define takes in two or, optionally, three arguments: the first is the element's value, the second is the element's key, and the third is a value supplied to array_walk( ) when it is called. For instance, here's another way to print table columns made of the values from an array: function print_row($value, $key) { print("$value$key\n");
}
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
array_walk($person, 'print_row');

A variation of this example specifies a background color using the optional third argument to array_walk( ). This parameter gives us the flexibility we need to print many tables, with many background colors:

function print_row($value, $key, $color) {
print("$value$key\n");
}
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
array_walk($person, 'print_row', 'blue');

The array_walk( ) function processes elements in their internal order.

Reducing an Array

A cousin of array_walk( ), array_reduce( ), applies a function to each element of the array in turn, to build a single value:

$result = array_reduce(array, function_name [, default ]);

The function takes two arguments: the running total, and the current value being processed. It should return the new running total. For instance, to add up the squares of the values of an array, use:

function add_up ($running_total, $current_value) {
$running_total += $current_value * $current_value;
return $running_total;
}

$numbers = array(2, 3, 5, 7);
$total = array_reduce($numbers, 'add_up');
// $total is now 87

The array_reduce( ) line makes these function calls:

add_up(2,3)
add_up(13,5)
add_up(38,7)

The default argument, if provided, is a seed value. For instance, if we change the call to array_reduce( ) in the previous example to:

$total = array_reduce($numbers, 'add_up', 11);

The resulting function calls are:

add_up(11,2)
add_up(13,3)
add_up(16,5)
add_up(21,7)

If the array is empty, array_reduce( ) returns the default value. If no default value is given and the array is empty, array_reduce( ) returns NULL.

Searching for Values

The in_array( ) function returns true or false, depending on whether the first argument is an element in the array given as the second argument:

if (in_array(to_find, array [, strict])) { ... }

If the optional third argument is true, the types of to_find and the value in the array must match. The default is to not check the types.

Here's a simple example:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
'root@example.com');
$got_spam = in_array('spam@cyberpromo.net', $addresses); // $got_spam is true
$got_milk = in_array('milk@tucows.com', $addresses); // $got_milk is false

PHP automatically indexes the values in arrays, so in_array( ) is much faster than a loop that checks every value to find the one you want.

Example 5-2 checks whether the user has entered information in all the required fields in a form.

Example 5-2: Searching an array

You ';
echo have_required($_POST, array('name', 'email_address')) ? 'did' : 'did not';
echo ' have all the required fields.

';
}
?>
" method="post">


Name:

Email address:

Age (optional):








A variation on in_array( ) is the array_search( ) function. While in_array( ) returns true if the value is found, array_search( ) returns the key of the found element:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$k = array_search($person, 'Wilma');
echo("Fred's $k is Wilma\n");
Fred's wife is Wilma

The array_search( ) function also takes the optional third strict argument, which requires the types of the value being searched for and the value in the array to match.

Sorting

Sorting changes the internal order of elements in an array and optionally rewrites the keys to reflect this new order. For example, you might use sorting to arrange a list of scores from biggest to smallest, to alphabetize a list of names, or to order a set of users based on how many messages they posted.

PHP provides three ways to sort arrays--sorting by keys, sorting by values without changing the keys, or sorting by values and then changing the keys. Each kind of sort can be done in ascending order, descending order, or an order defined by a user-defined function.

Sorting One Array at a Time

The functions provided by PHP to sort an array are shown in Table 5-1.

Table 5-1: PHP functions for sorting an array

Effect


Ascending


Descending


User-defined order

Sort array by values, then reassign indexes starting with 0


sort( )


rsort( )


usort( )

Sort array by values


asort( )


arsort( )


uasort( )

Sort array by keys


ksort( )


krsort( )


uksort( )

The sort( ), rsort( ), and usort( ) functions are designed to work on indexed arrays, because they assign new numeric keys to represent the ordering. They're useful when you need to answer questions like "what are the top 10 scores?" and "who's the third person in alphabetical order?" The other sort functions can be used on indexed arrays, but you'll only be able to access the sorted ordering by using traversal functions such as foreach and next.

To sort names into ascending alphabetical order, you'd use this:

$names = array('cath', 'angela', 'brad', 'dave');
sort($names); // $names is now 'angela', 'brad', 'cath', 'dave'

To get them in reverse alphabetic order, simply call rsort( ) instead of sort( ).

If you have an associative array mapping usernames to minutes of login time, you can use arsort( ) to display a table of the top three, as shown here:

$logins = array('njt' => 415,
'kt' => 492,
'rl' => 652,
'jht' => 441,
'jj' => 441,
'wt' => 402);
arsort($logins);
$num_printed = 0;
echo("\n");
foreach ($logins as $user => $time ) {
echo("\n");
if (++$num_printed == 3) {
break; // stop after three
}
}
echo("
$user$time
\n");




rl652
kt492
jht441


If you want that table displayed in ascending order by username, use ksort( ):

ksort($logins);
echo("\n");
foreach ($logins as $user => $time) {
echo("\n");
}
echo("
$user$time
\n");







jht441
jj441
kt492
njt415
rl652
wt402


User-defined ordering requires that you provide a function that takes two values and returns a value that specifies the order of the two values in the sorted array. The function should return 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if the values are the same for the purposes of your custom sort order.

Example 5-3 is a program that lets you try the various sorting functions on the same data.

Example 5-3: Sorting arrays

'Buzz Lightyear',
'email_address' => 'buzz@starcommand.gal',
'age' => 32,
'smarts' => 'some');

if($submitted) {
if($sort_type == 'usort' || $sort_type == 'uksort' || $sort_type == 'uasort') {
$sort_type($values, 'user_sort');
}
else {
$sort_type($values);
}
}
?>




Standard sort

Reverse sort

User-defined sort

Key sort

Reverse key sort

User-defined key sort

Value sort

Reverse value sort

User-defined value sort








Values :




    $value) {
    echo "
  • $key: $value
  • ";
    }
    ?>



Natural-Order Sorting

PHP's built-in sort functions correctly sort strings and numbers, but they don't correctly sort strings that contain numbers. For example, if you have the filenames ex10.php, ex5.php, and ex1.php, the normal sort functions will rearrange them in this order: ex1.php, ex10.php, ex5.php. To correctly sort strings that contain numbers, use the natsort( ) and natcasesort( ) functions:

$output = natsort(input);
$output = natcasesort(input);

Sorting Multiple Arrays at Once

The array_multisort( ) function sorts multiple indexed arrays at once:

array_multisort(array1 [, array2, ... ]);

Pass it a series of arrays and sorting orders (identified by the SORT_ASC or SORT_DESC constants), and it reorders the elements of all the arrays, assigning new indexes. It is similar to a join operation on a relational database.

Imagine that you have a lot of people, and several pieces of data on each person:

$names = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Joe');
$ages = array(25, 35, 29, 35, 35);
$zips = array(80522, '02140', 90210, 64141, 80522);

The first element of each array represents a single record--all the information known about Tom. Similarly, the second element constitutes another record--all the information known about Dick. The array_multisort( ) function reorders the elements of the arrays, preserving the records. That is, if Dick ends up first in the $names array after the sort, the rest of Dick's information will be first in the other arrays too. (Note that we needed to quote Dick's zip code to prevent it from being interpreted as an octal constant.)

Here's how to sort the records first ascending by age, then descending by zip code:

array_multisort($ages, SORT_ASC, $zips, SORT_DESC, $names, SORT_ASC);

We need to include $names in the function call to ensure that Dick's name stays with his age and zip code. Printing out the data shows the result of the sort:

echo("\n");
for ($i=0; $i <>\n");
}
echo("
$ages[$i]$zips[$i]$names[$i]
\n");






2580522Tom
2990210Harriet
3580522Joe
3564141Brenda
3502140Dick


Reversing Arrays

The array_reverse( ) function reverses the internal order of elements in an array:

$reversed = array_reverse(array);

Numeric keys are renumbered starting at 0, while string indexes are unaffected. In general, it's better to use the reverse-order sorting functions instead of sorting and then reversing the order of an array.

The array_flip( ) function returns an array that reverses the order of each original element's key-value pair:

$flipped = array_flip(array);

That is, for each element of the array whose value is a valid key, the element's value becomes its key and the element's key becomes its value. For example, if you have an array mapping usernames to home directories, you can use array_flip( ) to create an array mapping home directories to usernames:

$u2h = array('gnat' => '/home/staff/nathan',
'rasmus' => '/home/elite/rasmus',
'ktatroe' => '/home/staff/kevin');
$h2u = array_flip($u2h);
$user = $h2u['/home/staff/kevin']; // $user is now 'ktatroe'

Elements whose original values are neither strings nor integers are left alone in the resulting array. The new array lets you discover the key in the original array given its value, but this technique works effectively only when the original array has unique values.

Randomizing Order

To traverse the elements in an array in a random order, use the shuffle( ) function. All existing keys, whether string or numeric, are replaced with consecutive integers starting at 0.

Here's how to randomize the order of the days of the week:

$days = array('Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
shuffle($days);
print_r($days);
Array
(
[0] => Tuesday
[1] => Thursday
[2] => Monday
[3] => Friday
[4] => Wednesday
[5] => Saturday
[6] => Sunday
)

Obviously, the order after your shuffle( ) may not be the same as the sample output here. Unless you are interested in getting multiple random elements from an array, without repeating any specific item, using the rand( ) function to pick an index is more efficient.

Acting on Entire Arrays

PHP has several useful functions for modifying or applying an operation to all elements of an array. You can merge arrays, find the difference, calculate the total, and more, all using built-in functions.

Calculating the Sum of an Array

The array_sum( ) function adds up the values in an indexed or associative array:

$sum = array_sum(array);

For example:

$scores = array(98, 76, 56, 80);
$total = array_sum($scores);
// $total = 310

Merging Two Arrays

The array_merge( ) function intelligently merges two or more arrays:

$merged = array_merge(array1, array2 [, array ... ])

If a numeric key from an earlier array is repeated, the value from the later array is assigned a new numeric key:

$first = array('hello', 'world'); // 0 => 'hello', 1 => 'world'
$second = array('exit', 'here'); // 0 => 'exit', 1 => 'here'
$merged = array_merge($first, $second);
// $merged = array('hello', 'world', 'exit', 'here')

If a string key from an earlier array is repeated, the earlier value is replaced by the later value:

$first = array('bill' => 'clinton', 'tony' => 'danza');
$second = array('bill' => 'gates', 'adam' => 'west');
$merged = array_merge($first, $second);
// $merged = array('bill' => 'gates', 'tony' => 'danza', 'adam' => 'west')

Calculating the Difference Between Two Arrays

The array_diff( ) function identifies values from one array that are not present in others:

$diff = array_diff(array1, array2 [, array ... ]);

For example:

$a1 = array('bill', 'claire', 'elle', 'simon', 'judy');
$a2 = array('jack', 'claire', 'toni');
$a3 = array('elle', 'simon', 'garfunkel');
// find values of $a1 not in $a2 or $a3
$diff = array_diff($a1, $a2, $a3);
// $diff is array('bill', 'judy');

Values are compared using ===, so 1 and "1" are considered different. The keys of the first array are preserved, so in $diff the key of 'bill' is 0 and the key of 'judy' is 4.

Filtering Elements from an Array

To identify a subset of an array based on its values, use the array_filter( ) function:

$filtered = array_filter(array, callback);

Each value of array is passed to the function named in callback. The returned array contains only those elements of the original array for which the function returns a true value. For example:

function is_odd ($element) {
return $element % 2;
}
$numbers = array(9, 23, 24, 27);
$odds = array_filter($numbers, 'is_odd');
// $odds is array(0 => 9, 1 => 23, 3 => 27)

As you see, the keys are preserved. This function is most useful with associative arrays.

Using Arrays

Arrays crop up in almost every PHP program. In addition to their obvious use for storing collections of values, they're also used to implement various abstract data types. In this section, we show how to use arrays to implement sets and stacks.

Sets

Arrays let you implement the basic operations of set theory: union, intersection, and difference. Each set is represented by an array, and various PHP functions implement the set operations. The values in the set are the values in the array--the keys are not used, but they are generally preserved by the operations.

The union of two sets is all the elements from both sets, with duplicates removed. The array_merge( ) and array_unique( ) functions let you calculate the union. Here's how to find the union of two arrays:

function array_union($a, $b) {
$union = array_merge($a, $b); // duplicates may still exist
$union = array_unique($union);

return $union;
}

$first = array(1, 'two', 3);
$second = array('two', 'three', 'four');
$union = array_union($first, $second);
print_r($union);
Array
(
[0] => 1
[1] => two
[2] => 3
[4] => three
[5] => four
)

The intersection of two sets is the set of elements they have in common. PHP's built-in array_intersect( ) function takes any number of arrays as arguments and returns an array of those values that exist in each. If multiple keys have the same value, the first key with that value is preserved.

Another common function to perform on a set of arrays is to get the difference; that is, the values in one array that are not present in another array. The array_diff( ) function calculates this, returning an array with values from the first array that are not present in the second.

The following code takes the difference of two arrays:

$first = array(1, 'two', 3);
$second = array('two', 'three', 'four');
$difference = array_diff($first, $second);
print_r($difference);
Array
(
[0] => 1
[2] => 3
)

Stacks

Although not as common in PHP programs as in other programs, one fairly common data type is the last-in first-out (LIFO) stack. We can create stacks using a pair of PHP functions, array_push( ) and array_pop( ). The array_push( ) function is identical to an assignment to $array[]. We use array_push( ) because it accentuates the fact that we're working with stacks, and the parallelism with array_pop() makes our code easier to read. There are also array_shift( ) and array_unshift( ) functions for treating an array like a queue.

Stacks are particularly useful for maintaining state. Example 5-4 provides a simple state debugger that allows you to print out a list of which functions have been called up to this point (i.e., the stack trace).

Example 5-4: State debugger

$call_trace = array( );

function enter_function($name) {
global $call_trace;
array_push($call_trace, $name); // same as $call_trace[] = $name

echo "Entering $name (stack is now: " . join(' -> ', $call_trace) . ')
';
}

function exit_function( ) {
echo 'Exiting
';

global $call_trace;
array_pop($call_trace); // we ignore array_pop( )'s return value
}

function first( ) {
enter_function('first');
exit_function( );
}

function second( ) {
enter_function('second');
first( );
exit_function( );
}

function third( ) {
enter_function('third');
second( );
first( );
exit_function( );
}

first( );
third( );

Here's the output from Example 5-4:

Entering first (stack is now: first)
Exiting
Entering third (stack is now: third)
Entering second (stack is now: third -> second)
Entering first (stack is now: third -> second -> first)
Exiting
Exiting
Entering first (stack is now: third -> first)
Exiting
Exiting