You are on page 1of 72

.

HTML Text Formatting Elements

<i> Defines a part of text in an alternate voice or mood

<small> Defines smaller text

<strong> Defines important text

<ins> Defines inserted text

<del> Defines deleted text

<mark> Defines marked/highlighted text

HTML Table Tags

Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

HTML Table - Cell Padding


Cell padding is the space between the cell edges and the cell content.
By default, the padding is set to 0.
HTML Table - Cell Spacing
Cell spacing is the space between each cell. By default, the space is set to 2 pixels.

HTML Ordered List


In the ordered HTML lists, all the list items are marked with numbers by default. It is known
as numbered list also. The ordered list starts with <ol> tag and the list items start with <li>
tag.
<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>
Output:
1. Aries
2. Bingo
3. Leo
4. Oracle
The type Attribute.
You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it
is a disc. Following are the possible options.
<ul type = "square">
<ul type = "disc">
<ul type = "circle">
Example:
<ul type = "square">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
Output:
 Beetroot
 Ginger
 Potato
 Radish
HTML Unordered List
In HTML Unordered list, all the list items are marked with bullets. It is also known as
bulleted list also. The Unordered list starts with <ul> tag and list items start with the <li> tag.
<ul>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ul>
Output:
o Aries
o Bingo
o Leo
o Oracle
The type Attribute:
You can use type attribute for <ol> tag to specify the type of numbering you like. By default,
it is a number. Following are the possible options −
<ol type = "1"> - Default-Case Numerals.
<ol type = "I"> - Upper-Case Numerals.
<ol type = "i"> - Lower-Case Numerals.
<ol type = "A"> - Upper-Case Letters.
<ol type = "a"> - Lower-Case Letters.
The start Attribute.
You can use start attribute for <ol> tag to specify the starting point of numbering you need.
Following are the possible options −
<ol type = "1" start = "4"> - Numerals starts with 4.
<ol type = "I" start = "4"> - Numerals starts with IV.
<ol type = "i" start = "4"> - Numerals starts with iv.
<ol type = "a" start = "4"> - Letters starts with d.
<ol type = "A" start = "4"> - Letters starts with D.
Definition List
HTML Description list is also a list style which is supported by HTML and XHTML. It is
also known as definition list where entries are listed like a dictionary or encyclopaedia.
The definition list is very appropriate when you want to present glossary, list of terms or
another name-value list.
The HTML definition list contains following three tags:
1. <dl> tag defines the start of the list.
2. <dt> tag defines a term.
3. <dd> tag defines the term definition (description).
<dl>
<dt>Aries</dt>
<dd>-One of the 12 horoscope sign. </dd>
<dt>Bingo</dt>
<dd>-One of my evening snacks</dd>
<dt>Leo</dt>
<dd>-It is also a one of the 12-horoscope sign. </dd>
<dt>Oracle</dt>
<dd>-It is a multinational technology corporation. </dd>
</dl>

Output:

Aries
-One of the 12 horoscope sign.
Bingo
-One of my evening snacks
Leo
-It is also a one of the 12-horoscope sign.
Oracle
-It is a multinational technology corporation.

Anchor tag
The <a> tag defines a hyperlink, which is used to link from one page to another.
The most important attribute of the <a> element is the href attribute, which indicates the
link's destination.
By default, links will appear as follows in all browsers:
 An unvisited link is underlined and blue.
 A visited link is underlined and purple.
 An active link is underlined and red.
<a href="https://www.w3schools.com">Visit W3Schools.com! </a>

Name Attribute:
The name attribute specifies a name for an HTML element.
This name attribute can be used to reference the element in a JavaScript.
For a <form> element, the name attribute is used as a reference when the data is submitted.
Applies to
The name attribute can be used on the following elements:

Elements Attribute

<button> name

<form> name

<input> name

<map> name
<meta> name

<textarea> name

HTML Links - The target Attribute


By default, the linked page will be displayed in the current browser window. To change this,
you must specify another target for the link.
The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
 _self - Default. Opens the document in the same window/tab as it was clicked.
 _blank - Opens the document in a new window or tab.
 _parent - Opens the document in the parent frame.
 _top - Opens the document in the full body of the window.
HTML Links - Use an Image as a Link
To use an image as a link, just put the <img> tag inside the <a> tag:
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px; height:42px;">
</a>
Output:

Link to an Email Address:


Use mailto: inside the href attribute to create a link that opens the user's email program (to let
them send a new email):
Example:
<a href="mailto:someone@example.com">Send email</a>
Button as a Link:
To use an HTML button as a link, you have to add some JavaScript code.
JavaScript allows you to specify what happens at certain events, such as a click of a button:
Example
<button onclick="document.location='default.asp'">HTML Tutorial</button>
Output:

HTTP HTTPS

The full form of HTTP is the The full form of HTTPS is Hypertext Transfer
Hypertext Transfer Protocol. Protocol Secure.

It is written in the address bar as It is written in the address bar as https://.


http://.

The HTTP transmits the data over The HTTPS transmits the data over port number
port number 80. 443.

It is unsecured as the plain text is It is secure as it sends the encrypted data which
sent, which can be accessible by hackers cannot understand.
the hackers.

It is mainly used for those It is a secure protocol, so it is used for those


websites that provide information websites that require to transmit the bank account
like blog writing. details or credit card numbers.

It is an application layer protocol. It is a transport layer protocol.

It does not use SSL. It uses SSL that provides the encryption of the
data.

Google does not give the Google gives preferences to the HTTPS as
preference to the HTTP websites. HTTPS websites are secure websites.

The page loading speed is fast. The page loading speed is slow as compared to
HTTP because of the additional feature that it
supports, i.e., security.
FTP
o FTP stands for File transfer protocol.
o FTP is a standard internet protocol provided by TCP/IP used for transmitting the files
from one host to another.
o It is mainly used for transferring the web page files from their creator to the computer
that acts as a server for other computers on the internet.
o It is also used for downloading the files to computer from other servers.
Objectives of FTP
o It provides the sharing of files.
o It is used to encourage the use of remote computers.
o It transfers the data more reliably and efficiently.

HTML <form> Tag


An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing
such as name, email address, password, phone number, etc.
HTML Form Tags
Let's see the list of HTML 5 form tags.

Tag Description

<form> It defines an HTML form to enter inputs by the used side.

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

<fieldset> It groups the related element in a form.


<legend> It defines a caption for a <fieldset> element.

<select> It defines a drop-down list.

<optgroup> It defines a group of related options in a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

HTML <input> element


The HTML <input> element is fundamental form element. It is used to create form fields, to
take input from user. We can apply different input filed to gather different information form
user. Following is the example to show the simple text input.
Example:
<body>
<form>
Enter your name <br>
<input type="text" name="username">
</form>
</body>
Output:

Following is a list of all types of <input> element of HTML.

type="” Description

text Defines a one-line text input field

password Defines a one-line password input field


submit Defines a submit button to submit the form to server

reset Defines a reset button to reset all values in the form.

radio Defines a radio button which allows select one option.

checkbox Defines checkboxes which allow select multiple options form.

button Defines a simple push button, which can be programmed to perform a task on an
event.

file Defines to select the file from device storage.

image Defines a graphical submit button.

HTML5 added new types on <input> element. Following is the list of types of elements
of HTML5.

type=" " Description

color Defines an input field with a specific color.

date Defines an input field for selection of date.

datetime-local Defines an input field for entering a date without time zone.

email Defines an input field for entering an email address.

month Defines a control with month and year, without time zone.

number Defines an input field to enter a number.

url Defines a field for entering URL

week Defines a field to enter the date with week-year, without time zone.

search Defines a single line text field for entering a search string.
tel Defines an input field for entering the telephone number.

HTML TextField Control


The type="text" attribute of input tag creates textfield control also known as single line
textfield control. The name attribute is optional, but it is required for the server side
component such as JSP, ASP, PHP etc.
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>

HTML <textarea> tag in form


The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute or by CSS.
<body>
<form>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
</form>
</body>
Label Tag in Form
It is considered better to have label in form. As it makes the code parser/browser/user
friendly.
If you click on the label tag, it will focus on the text control. To do so, you need to have
for attribute in label tag that must be same as id attribute of input tag.
<form>
<label for="firstname">First Name: </label> <br/>
<input type="text" id="firstname" name="firstname"/> <br/>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"/> <br/>
</form>

HTML Password Field Control


The password is not visible to the user in password field control.
<form>
<label for="password">Password: </label>
<input type="password" id="password" name="password"/> <br/>
</form>
Output:

Email Field Control


The email field in new in HTML 5. It validates the text for correct email address. You
must use @ and . in this field.
<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
It will display in browser like below:

Radio Button Control


 The radio button is used to select one option from multiple options. It is used for
selection of gender, quiz questions etc.
 If you use one name for all the radio buttons, only one radio button can be
selected at a time.
 Using radio buttons for multiple options, you can only choose a single option at a
time.
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>
</form>

Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>

Submit button control.


HTML <input type="submit"> are used to add a submit button on web page. When user
clicks on submit button, then form get submit to the server.
Syntax:
<input type="submit" value="submit">
The type = submit, specifying that it is a submit button
The value attribute can be anything which we write on button on web page.
The name attribute can be omitted here.
Example:
<form>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
HTML action attribute
The action attribute of <form> element defines the process to be performed on form when
form is submitted, or it is a URI to process the form information.
The action attribute value defines the web page where information proceeds. It can
be .php, .jsp, .asp, etc. or any URL where you want to process your form.
Note: If action attribute value is blank then form will be processed to the same page.
Example:
<form action="action.html" method="post">
<label>User Name:</label><br>
<input type="text" name="name"><br><br>
<label>User Password</label><br>
<input type="password" name="pass"><br><br>
<input type="submit">
</form>

HTML method attribute


The method attribute defines the HTTP method which browser used to submit the form.
The possible values of method attribute can be:
o post: We can use the post value of method attribute when we want to process the
sensitive data as it does not display the submitted data in URL.
Example:
<form action="action.html" method="post">
o get: The get value of method attribute is default value while submitting the form. But
this is not secure as it displays data in URL after submitting the form.
Example:
<form action="action.html" method="get">
When submitting the data, it will display the entered data in the form of:
file:///D:/HTML/action.html?name=JavaTPoint&pass=123

unit-2
Levels of Style Sheets
There are three levels of style sheets.
• Inline - specified for a specific occurrence of a tag and apply only to that tag. This is fine
grain style, which defeats the purpose of style sheets - uniform style.
• Document-level style sheets - apply to the whole document in which they appear
• External style sheets - can be applied to any number of documents
• When more than one style sheet applies to a specific tag in a document, the lowest level
style sheet has precedence
• For eg: if an external style sheet specifies a value for a particular property of a particular
tag, that value is used until a different value is specified in either a document style sheet or an
inline style sheet
• Likewise, a document style sheet property value can be overridden by different property
values in an inline style sheet
• Inline style sheets appear in the tag itself.
• Document-level style sheets appear in the head of the document
• External style sheets are in separate files; they can be stored on any computer on the web.
The browser fetches just as it fetches documents.
Style specification formats:
A CSS rule consists of a selector and a declaration block.
CSS Syntax
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.

Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue, and the text color of
the <p> element to red:Format depends on the level of the style sheet:
Example:
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;">A Blue Heading</h1>
<p style="color:red;">A red paragraph.</p>
</body>
</html>
Output:
Selector Forms:
The selector can have variety of forms:
1. Simple selector form
2. Class selector
3. Id selector
4. Contexual Selectors
5. Universal selector
6. Pseudo classes
1.Simple selector forms
• The selector is a tag name or a list of tag names, separated by commas
• Consider the following examples, in which the property is font-size and the property value
is a number of points :
• h1, h3 { font-size: 24pt ;}
• h2 { font-size: 20pt ;}
2.Class Selector
• Used to allow different occurrences of the same tag to use different style specifications
• A style class has a name, which is attached to a tag name
p.normal {property/value list}
p.warning{property/value list}
• The class you want on a particular occurrence of a tag is specified with the class attribute of
the tag
• For example,
<p class = "normal">
A paragraph of text that we want to be presented in ‘normal’
presentation style</p>
<p class = "warning">
A paragraph of text that is a warning to the reader ,which should be
presented in an especially noticeable style.
</p>
CLASSES
• HTML and XHTML require each id be unique– therefore an id
value can only be used once in a document.
• You can mark a group of elements with a common identifier
using the class attribute.
3.id Selectors
• An id selector allow the application of a style to one specific element.
• General form:
#specific-id {property-value list}
Example:
#section14 {font-size: 20}
Specifies a font size of 20 points to the element
<h2 id = “section14”>Hello</h2>
4.Contexual selectors
• Selectors can also specify that the style should apply only to elements in certain positions in
the
document .This is done by listing the element hierarchy in the selector.
Eg: body b em {font-size: 24pt ;}
• In the eg, selector applies its style to the content of emphasis elements that are descendants
of bold elements in the body of the document.
It is also called as descendant selectors. It will not apply to emphasis element not descendant
of bold face element.
5.Universal Selectors
• The universal selector denoted by an asterisk(*). It applies its style to all elements in the
document
For Eg:
* {color : red}
Makes all elements in the document red.
6.Pseudo Classes
• Pseudo classes are styles that apply when something happens, rather than because the target
element(tag) simply exists. Names begin with colons
The style of hover pseudo classes apply when the mouse cursor is over the element.The style
of focus pseudo classes apply when an element has focus (mouse cursor over the element and
click the left mouse button)
Example:
• Input:hover {color: red;}
Pseudo Class Example
<!-- pseudo.html -->
<!DOCYPE html>
<html lang=”en”>
<head>
<title>Pseudoclasses</title>
<meta charset=”utf-8” />
<style type = "text/css">
input:hover {color: red;}
input:focus {color: green;}
</style>
</head>
<body>
<form action = "">
<p>
Your name:
<input type = "text" />
</p>
</form>
</body>
</html>

Property Value Forms


• CSS1 include 60 different properties in 7 categories:
• Fonts
• Lists
• Alignment of text
• Margins
• Colors
• Backgrounds
• Borders
Property Values (values of properties)
The property value can appear in many forms.
• Keywords – large,medium, small, …
• Number values – integers,decimal numbers etc.
• Length - numbers, maybe with decimal points followed by two character
abbreviation of a unit name
• Units:
• px - pixels
• in - inches
• cm - centimeters
• mm - millimeters
• pt - points
• pc - picas (12 points)
• em – value of the current font size in pixels
• ex - height of the letter ‘x’
• No space is allowed between the number and the unit specification e.g., 1.5 in is
illegal!
Eg: 10px, 24pt etc.
• Percentage - just a number followed immediately by a percent sign. Eg: 70%
• URL values
• url(protocol://server/pathname)
• Colors
• Color name: eg: fuchsia
• rgb(n1, n2, n3) :Eg: rgb(255,0,255)
• Numbers can be decimal or percentages
• Hexadecimal form: hexadecimal numbers must be preceded with pound(#) sign.
Eg : #B0E0E6 stands for powder blue color.
JAVASCRIPT
It was introduced in the year 1995 for adding programs to the webpages in the Netscape
Navigator browser

Disadvantages of External JavaScript


 There are the following disadvantages of external files:
 The stealer may download the coder's code using the url of the js file.
 If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
 The web browser needs to make an additional http request to get the js code.
 A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
 We need to check each file that depends on the commonly created external javascript
file.
 If it is a few lines of code, then better to implement the internal javascript code.
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
 Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different variables.

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types
of data types in JavaScript.
 Primitive data type
 Non-primitive (reference) data type
JavaScript is a dynamic type of language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here to
specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of 10==20 = false


same type)

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30


-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement

Let’s see the simple example of if statement in javascript.


<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
Output of the above example
a is even number
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Output:
1
2
3
4
5
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.
Syntax:
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Output:
11
12
13
14
15
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.
Syntax:
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
Output:
21
22
23
24
25
JavaScript Functions
A function (also known as a method) is a self-contained piece of code that performs a
particular "function". You can recognise a function by its format - it's a piece of
descriptive text, followed by openand close brackets.A function is a reusable code-block
that will be executed by an event, or when the function is called.
To keep the browser from executing a script when the page loads, you can put your script
into a function.A function contains code that will be executed by an event or by a call to
that function.
You may call a function from anywhere within the page (or even from other pages if the
function isembedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document.
However, to assure that the function is read/loaded by the browser before it is called, it
could be wise to put it in the <head> section.
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" >
</form>
</body>
</html>
If the line: alert("Hello world!!") in the example above had not been put within a
function, it would havebeen executed as soon as the line was loaded. Now, the script is
not executed before the user hits the button. We have added an onClick event to the
button that will execute the function displaymessage() when the button is clicked.
How to Define a Function
The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the function. The { and the } defines the
start and end ofthe function.
Note: A function with no parameters must include the parentheses () after the function
name:
Note: Do not forget about the importance of capitals in JavaScript! The word function
must be written inlowercase letters, otherwise a JavaScript error occurs! Also note that
you must call a function with the exact same capitals as in the function name.
The return Statement
The return statement is used to specify the value that is returned from the
function.So, functions that are going to return a value must use the
return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3);
The returned value from the prod() function is 6, and it will be stored in the variable
called product.
The Lifetime of JavaScript Variables
When you declare a variable within a function, the variable can only be accessed within
that function. When you exit the function, the variable is destroyed. These variables are
called local variables. You canhave local variables with the same name in different
functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it.
The lifetime ofthese variables starts when they are declared, and ends when the page is
closed.
There are 3 types of pop-up boxes:
 Alert
 Confirm
 Prompt
The alert method opens a dialog window and displays its parameter in that window. It
also displays an OK button.
The string parameter of alert is not XHTML code; it is plain text.
Therefore, the string parameter of alert may include \n but never should include <br />.
alert(“The sum is:” + sum + “\n”);

The confirm method opens a dialog window in which the method displays its string
parameter, along with two buttons: OK and Cancel. confirm returns a Boolean value that
indicates the user’s button input: true for OK and false for Cancel. This method is often
used to offer the user the choice of continuing some process.
var question = confirm(“Do you want to continue this download?”);
After the user presses one of the buttons in the confirm dialog window, the script can test
the variable, question, and react accordingly.

The prompt method creates a dialog window that contains a text box used to collect a
string of input from the user, which prompt returns as its value.
o String – groups of quote delimited characters
o Boolean – true and false
o Array – Multiple data items in array format
o Object – instances of classes
o NULL – For variable that have not be given a value or have been unset.
o Resource – external resources like DB connections or file pointers
 There are numerous functions available for determining the data type of variables.
o getType( )
o is_array( )
o is_double( ), is_float( ), is_real( )
o is_long( ), is_int( ), is_integer( )
o is_string( )
o is_object( )
o is_resource( )
o is_null( )
o is_scalar( ) – check for integer, Boolean, string, or float
o is_numeric( ) – check for number or numeric string
o is_callable( ) – checks for valid function name
 Each of these takes a variable as an argument and returns true or false.
 There is also a settype($var, ‘type’ ) function that can be used to set a specific type
 Type can also be manipulated using casting.
// Casting
$totalamount = (float)$totalqty;
 Type can also be changed by using reinterpretation functions.
o intval($var )
o floatval ($var)
o strval ($var)
// Examples of Different type of data
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Data Types</title>
</head>
<body>
<?php
$name = "Victrola Firecracker";
$id = 123456789;
$age = 99.9;
echo "Name value: " . $name . "<br/>";
echo "Name type: " . getType( $name ) . "<br/>";
echo "<hr/>";
echo "ID value: " . $id . "<br/>";
echo "ID type: " . getType( $id ) . "<br/>";
echo "Is ID an integer? " . is_int( $id ) . "<br/>";
echo "<hr/>";
echo "Age value: " . $age . "<br/>";
echo "Age type: " . getType( $age ) . "<br/>";
echo "Is age real? " . is_real( $age ) . "<br/>";
?>
</body>
</html>
Variable Status
 isset() and empty( )
Constants
 Constants are variables whose value cannot be changed once it is set.
define(‘CONSTANT’, value );
 Constants do not use the $ prefix when they are being referred to.
 Constants can only store Boolean, integer, float, and string data (they are always
scalar)
<?php
define(‘TOTALPOINTS', 800 );
echo TOTALPOINTS;
?>
Variable Variables
 These are special types of variables whose identifiers are variable as is the variables
value.
 One variable is used as the identifier for another variable.
<?php
$id = "id123456789";
//assign value
$$id = "Victrola Firecracker";
//see value
echo $id123456789;
?>
Variable Scope
 At this point we know that all variables have an identifier, a data type, and a value.
 All variables also have a scope.
o The scope of a variable refers to the places in a script where a variable can be
used.
 PHP has 6 scopes that you should be aware of:
o Built in super global variables – can be used from anywhere.
o Constants – can be used inside and outside functions.
o Global variables – declared inside a script but outside a function can be used
anywhere in the script except inside the functions.
o Global variables declared specifically as global inside a function can be used
anywhere in the script.
o Variables declared as static inside functions can be used from anywhere but
will retain their values from one execution of the function to the next
o Variables declared normally inside functions only exist inside that function
and cease to exist when the function ends.
Passing Variables Between Pages
 Variable values can be passed from one page to another in PHP through HTTP’s
normal GET and POST behaviors.
o This is most often used when passing values from forms to be processed by
PHP but can be used in other ways.
 A value is passed from one page to another by appending a question mark followed by
the variables name, an equal sign, and the variables value to the end of the URL for
the page that the value is being passed to as a normal hyperlink.
// Example URL for Requesting a page
<a href="receiver.php?fname=victrola">Send name</a>
 The value can then be accessed from the receiving page three different ways
depending on the PHP server’s setup.
o Short Method
 $fname, if the server allows the name and value that are passed to the
page will take the form of a normal PHP variable.
 It allows simple quick access to the variable and its value but can cause
security problems, so this is normally turned off (default)
o Medium Method
 An array of global variables that are always accessible called $_GET
and $_POST is available that each passed variable will be assigned to.
 This is the preferred method used today.
o Long Method
 Another global array called either $HTTP_GET_VARS or
$HTTP_POST_VARS can also be used.
 This method is acceptable but can also be turned off.
// receiver.php
echo $_GET [ 'fname' ];
 Multiple value can be sent by separating each name/value pair with an ampersand (&)
// updated url and receiver.php
<a href="receiver.php?fname=victrola&lname=firecracker">
Send name
</a>
echo "First name received is " . $_GET [ 'fname' ] ."<br/>";
echo "Last name received is " . $_GET [ 'lname' ];
 The same thing can be accomplished while keeping the data dynamic (not hard coded)
by supplying the user with a form to complete.
 The form should be standard (X)HTML with the action attribute set to the name of the
receiving page and the method set to either GET or POST.
o GET will allow the sent data to be seen in the address bar (insecure)
o POST will hind the data in the message request header (more secure)
 The HTML form will automatically create the needed URL to send the data to the
receiving page if GET is used.
// receiver.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="receiver.php" method="GET">
<table>
<tr>
<td>First Name</td>
<td>
<input type="text" name="fname"/>
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input type="text" name="lname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
Advantage of PHP Functions
1. Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
2. Less Code: It saves a lot of code because you don't need to write the logic many
times. By the use of function, you can write the logic only once and reuse it.
3. Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of
functions.
Functions in PHP
 A function is a self-contained block of code that performs a well-defined task, can be
passed values and can return values through a defined interface.
 Functions in php are NOT case sensitive.
 Built in functions are available to all scripts but user defined functions are only available
to scripts that include them.
Function Structure
 All functions begin with the keyword function, followed by the functions name, and a
set of parentheses.
 Function names should be short but descriptive.
o Functions cannot have the same name as other functions (no function
overloading in PHP)
o Can contain only letters, numbers, and underscores.
o Cannot begin with a digit.
 The function declaration is then followed by a set of curly braces that contain the
statements and expressions that will execute when the function is called.
 Functions can include any legal statement in PHP or HTML.
Understanding Variable scope:
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
 Local variables
 Function parameters
 Global variables
 Static variables
Local Variables
A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be an entirely different variable from
the one contained in the function −
<?php
$x = 4;
function assignx ()
{ $x = 0;
print "\$x inside function is $x. <br />"; }
assignx();
print "\$x outside of function is $x. <br />";
?>
This will produce the following result − $x inside function is 0. $x outside of function is 4.
Function Parameters
Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be –
<?php // multiply a value by 10 and return it to the caller
function multiply ($value)
{ $value = $value * 10; return $value; }
$retval = multiply (10);
Print "Return value is $retval\n";
?>
This will produce the following result − Return value is 100
Global Variables
In contrast to local variables, a global variable can be accessed in any part of the program.
However, in order to be modified, a global variable must be explicitly declared to be global in
the function in which it is to be modified. This is accomplished, conveniently enough, by
placing the keyword GLOBAL in front of the variable that should be recognized as global.
Placing this keyword in front of an already existing variable tells PHP to use the variable
having that name. Consider an example –
<?php
$somevar = 15;
function addit()
{ GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
} addit();
?>
This will produce the following result − Somevar is 16
Static Variables
The final type of variable scoping that I discuss is known as static. In contrast to the variables
declared as function parameters, which are destroyed on the function's exit, a static variable
will not lose its value when the function exits and will still hold that value should the function
be called again. You can declare a variable to be static simply by placing the keyword
STATIC in front of the variable name.
<?php
function keep_track()
{ STATIC $count = 0;
$count++;
print $count; print "<br />"; }
keep_track(); keep_track(); keep_track();
?>
This will produce the following result – 1 2 3
PHP’s Superglobal Variables
PHP offers several useful predefined variables that are accessible from anywhere within the
executing script and provide you with a substantial amount of environment-specific
information. You can sift through these variables to retrieve details about the current user
session, the user’s operating environment, the local operating environment, and more. PHP
creates some of the variables, while the availability and value of many of the other variables
are specific to the operating system and web server. Therefore, rather than attempt to
assemble a comprehensive list of all possible predefined variables and their possible values,
the following code will output all predefined variables pertinent to any given web server and
the script’s execution environment:
foreach ($_SERVER as $var => $value)
{ echo "$var => $value <br />"; }

Require () and include () in PHP


PHP require () Function: The require () function in PHP is basically used to include the
contents/code/data of one PHP file to another PHP file. During this process if there are any
kind of errors then this require () function will pop up a warning along with a fatal error and
it will immediately stop the execution of the script. In order to use this, require () function,
we will first need to create two PHP files. Using the include () function, include one PHP file
into another one. After that, you will see two PHP files combined into one HTML file.
Example 1:
 HTML

<html>
<body>
<h1>Welcome to geeks for geeks!</h1>
<p>Myself, Gaurav Gandal</p>
<p>Thank you</p>
<?php require 'GFG.php'; ?>
</body>
</html>

 GFG.php

<?php
echo "
<p>visit Again-" . date("Y") . " geeks for geeks.com</p>
";
?>

Output:

PHP include () Function: The include() function in PHP is basically used to include the
contents/code/data of one PHP file to another PHP file. During this process if there are any
kind of errors then this include () function will pop up a warning but unlike the require
() function, it will not stop the execution of the script rather the script will continue its
process. In order to use this, include () function, we will first need to create two PHP files.
Using the include () function, include one PHP file into another one. After that, you will see
two PHP files combined into one HTML file.
Example 2:
 HTML

<html>
<body>
<h1>Welcome to geeks for geeks!</h1>
<p>Myself, Gaurav Gandal</p>

<p>Thank you</p>

<?php include 'GFG.php'; ?>


</body>
</html>

 GFG.php

<?php
echo "
<p>Visit Again; " . date("Y") . " Geeks for geeks.com</p>
";
?>

Output:
Difference between require() and include():

include() require()

The include() function does not stop the The require() function will stop the
execution of the script even if any error execution of the script when an error
occurs. occurs.

The include() function does not give a fatal The require() function gives a fatal
error. error

The include() function is mostly used when


The require() function is mostly used
the file is not required and the application
when the file is mandatory for the
should continue to execute its process when
application.
the file is not found.

The include() function will only produce a The require() will produce a fatal error
warning (E_WARNING) and the script will (E_COMPILE_ERROR) along with the
continue to execute. warning.

Built-In Functions of PHP


 Built-in functions are the functions that are provided by PHP to make programming
more convenient.
 Many built-in functions are present in PHP which can be employed in our code. These
functions are very helpful in achieving programming goals.
 The built-in functions in PHP are very simple and easy to use. They make PHP
powerful and useful.
 PHP is very rich in terms of Built-in functions. Some of the important Built-in
functions of PHP are as follows:
PHP Array Functions
These functions allow interacting with and manipulating arrays in various ways. Arrays are
essential for storing, managing, and operating on sets of variables.
 array() - Create an array
 array_chunk() - Splits an array into chunks of arrays
 array_diff() - Compares array values, and returns the differences
 array_fill() - Fills an array with values
 array_intersect() - Compares array values, and returns the matches
 array_merge() - Merges one or more arrays into one array
PHP Calender Functions
The calendar extension presents a series of functions to simplify converting between different
calendar formats.
 cal_from_jd() - Returns information about a given calendar.
 cal_from_jd() - Converts a Julian day count into a date of a specified calendar.
 JDMonthName() - Returns a month name.
 JDDayOfWeek() - Returns the day of a week.
 jdtounix() - Converts a Julian day count to a Unix timestamp.
 unixtojd() - Converts a Unix timestamp to a Julian day count.
PHP Character Functions
The functions provided by this extension check whether a character or string falls into a
certain character class according to the current locale.
 ctype_alnum() - Check for alphanumeric character(s).
 ctype_alpha() - Check for alphabetic character(s).
 ctype_digit() - Check for numeric character(s).
 ctype_space() - Check for whitespace character(s).
 ctype_upper() - Check for uppercase character(s).
 ctype_lower() - Check for lowercase character(s).
PHP Date & Time Functions
These functions allow getting the date and timing from the server where PHP scripts are
running. These functions are used to format the date and time in many different ways.
 date_date_set() - Sets the date.
 date_default_timezone_get() – Returns the default time zone.
 date_default_timezone_set() - Sets the default time zone.
 date_format() - Returns date formatted according to given format.
 date_time_set() - Sets the time.
 getdate() - Returns an array that contains date and time information for a Unix
timestamp.
 time() - Returns the current time as a Unix timestamp.
PHP Directory Functions
These functions are provided to manipulate any directory. PHP needs to be configured with --
enable-chroot-func option to enable chroot() function.
 chdir() - Changes current directory.
 chroot() - Change the root directory.
 dir() - Opens a directory handle and returns an object.
 closedir() - Closes a directory.
 getcwd() - Gets the current working directory.
 opendir() - Open directory handle.
PHP Error Handling Functions
These are functions dealing with error handling and logging. They allow user to define their
own error handling rules, as well as modify the way the errors can be logged. This allows
user to change and enhance error reporting to suit their needs.
Using these logging functions, user can send messages directly to other machines, to an
email, to system logs, etc. So user can selectively log and monitor the most important parts of
their applications and websites.
 error_log() - Sends an error to the server error-log, to a file or to a remote destination.
 error_reporting() - Specifies which errors are reported.
 set_error_handler()- Sets a user-defined function to handle errors.
 set_exception_handler() - Sets a user-defined function to handle exceptions.
 error_get_last() - Gets the last error occurred.
 trigger_error() - Creates a user-defined error message.
PHP MySQL Function
PHP MySQLi functions gives to access the MySQLi database servers. PHP works with
MySQLi version 4.1.13 or newer.
 mysqli connect - It opens a connection to a MySQLi Server.
 mysqli create db - It is used to create MySQLi connection.
 mysqli close - It is used to close MySQLi connection.
 mysqli ping - It is used to pings a server connection and reconnect to server if
connection is lost.
 mysqli query - It performs a query against the database.
 mysqli real connect - This function opens a new connection to the MySQLi.
 mysqli refresh - This function refreshes tables or caches or resets the replication
server information.
 mysqli_stat - This function returns the current system status.
 mysqli rollback - This function rolls back the current transaction for the specified
database connection.
PHP File System Functions
The file system functions are used to access and manipulate the file system. PHP provides all
the possible functions may need to manipulate a file.
 chmod() - Changes file mode.
 file_exists() - Checks whether a file or directory exists.
 file_get_contents() - Reads entire file into a string.
 file_put_contents() - Write a string to a file.
 file() - Reads entire file into an array.
 basename() - Returns filename component of path.
PHP String Functions
PHP string functions are the part of the core. It manipulate strings in almost any possible way.
 chop() - It is used to removes whitespace.
 chunk_split() - It is used to split a string into chunks.
 crypt() - It is used to hashing the string.
 str_split() - It is used to convert a string to an array.
 strchr() - It is used to searches for the first occurrence of a string inside another.
 trim() - It used to remove the white-spaces and other characters.
PHP Network Functions
PHP Network functions give access to internet from PHP.
 fsockopen() - It is used to open internet or Unix domain socket connections.
 gethostbyname() - It is used to get the internet host name which has given by IP
Address.
 gethostname() - It is used to get the host name.
 header() - It is used to send the row of HTTP Headers.
 openlog() - It used to open connection to system logger.
 setcookie() - It used to set the cookies.

Modifying Elements of an Array


After you've created an array, what about modifying it? No problem—you can
modify the values in arrays as easily as other variables. One way is to access an
element in an array simply by referring to it by index. For example, say you
have this array:
$fruits[1] = "pineapple";
$fruits[2] = "pomegranate";
$fruits[3] = "tangerine";
Now say you want to change the value of $fruits[2] to "watermelon". No
problem at all:
$fruits[1] = "pineapple";
$fruits[2] = "pomegranate";
$fruits[3] = "tangerine";
$fruits[2] = "watermelon";
Then say you wanted to add a new element, "grapes", to the end of the array.
You could do that by referring to $fruits[], which is PHP's shortcut for adding a
new element:
$fruits[0] = "pineapple";
$fruits[1] = "pomegranate";
$fruits[2] = "tangerine";
$fruits[2] = "watermelon";
$fruits[] = "grapes";
All that's left is to loop over the array and display the array contents, as shown
in Example 3-1, phparray.php.
You can also copy a whole array at once if you just assign it to another array:
<?php
$fruits[0] = "pineapple";
$fruits[1] = "pomegranate";
$fruits[2] = "tangerine";
$fruits[2] = "watermelon";
$fruits[] = "grapes";
$produce = $fruits;
echo $produce[2];
?>
This script gives you this output:
watermelon
Output:
3
Removing Element from an Array:
In order to remove an element from an array, we can use unset() function which
removes the element from an array and then use array_values() function which
indexes the array numerically automatically.
Function Used:
1. unset(): This function unsets a given variable.
Syntax:
void unset ( mixed $var [, mixed $... ] )
1. array_values(): This function returns all the values from the array and
indexes the array numerically.
Syntax:
array array_values ( array $array )
Example:

<?php
$arr1 = array(
'geeks', // [0]
'for', // [1]
'geeks' // [2]
);
// remove item at index 1 which is 'for'
unset($arr1[1]);
// Print modified array
var_dump($arr1);
// Re-index the array elements
$arr2 = array_values($arr1);
// Print re-indexed array
var_dump($arr2);
?>

Output:
array(2) {
[0]=>
string(5) "geeks"
[2]=>
string(5) "geeks"
}
array(2) {
[0]=>
string(5) "geeks"
[2]=>
string(5) "geeks"
}
The var_dump() function dumps information about one or more variables. The
information holds type and value of the variable(s).
Converting an Array to String:
The implode () method is an inbuilt function in PHP and is used to join the
elements of an array. The implode () method is an alias for PHP join ()
function and works exactly same as that of join () function.
Syntax:
string implode ($separator, $array)
Example:
 PHP

<?php
// Declare an array
$arr = array("Welcome","to", "GeeksforGeeks",
"A", "Computer","Science","Portal");
// Converting array elements into
// strings using implode function
echo implode(" ",$arr);
?>

Output:
Welcome to GeeksforGeeks A Computer Science Portal
Converting String to an Array:
The explode () function breaks a string into an array.
Note: The "separator" parameter cannot be an empty string.
Note: This function is binary-safe.
Syntax
explode(separator,string,limit)
Parameter Values

Parameter Description

separator Required. Specifies where to break the string

string Required. The string to split

limit Optional. Specifies the number of array elements to return.


Possible values:
 Greater than 0 - Returns an array with a maximum
of limit element(s)
 Less than 0 - Returns an array except for the last -
limit elements()
 0 - Returns an array with one element

Example:
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output:
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] =>
day. )
Multidimensional arrays
Multi-dimensional arrays are such type of arrays which stores another array at
each index instead of single element. In other words, define multi-dimensional
arrays as array of arrays. As the name suggests, every element in this array can
be an array and they can also hold other sub-arrays within. Arrays or sub-arrays
in multidimensional arrays can be accessed using multiple dimensions.
Dimensions: Dimensions of multidimensional array indicates the number of
indices needed to select an element. For a two-dimensional array two indices to
select an element.
Two-dimensional array: It is the simplest form of a multidimensional array. It
can be created using nested array. These types of arrays can be used to store any
type of elements, but the index is always a number. By default, the index starts
with zero.
Syntax:
array (
array (elements...),
array (elements...),
...
)

Example:

<?php
// PHP program to create
// multidimensional array
// Creating multidimensional
// array
$myarray = array(

// Default key for each will


// start from 0
array("Ankit", "Ram", "Shyam"),
array("Unnao", "Trichy", "Kanpur")
);
// Display the array information
print_r($myarray);
?>

Output:
Array
(
[0] => Array
(
[0] => Ankit
[1] => Ram
[2] => Shyam
)
[1] => Array
(
[0] => Unnao
[1] => Trichy
[2] => Kanpur
)
)
Two-dimensional associative array: Al associative array is similar to indexed
array but instead of linear storage (indexed storage), every value can be
assigned with a user-defined key of string type.
Example:
<?php

// PHP program to creating two


// dimensional associative array
$marks = array(
// Ankit will act as key
"Ankit" => array(
// Subject and marks are
// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),
// Ram will act as key
"Ram" => array(
// Subject and marks are
// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),
// Anoop will act as key
"Anoop" => array(
// Subject and marks are
// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);
echo "Display Marks: \n";
print_r($marks);
?>

Output:
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
[FOL] => 46
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
[FOL] => 99
)
)
Three-Dimensional Array: It is the form of multidimensional array.
Initialization in Three-Dimensional array is same as that of Two-dimensional
arrays. The difference is as the number of dimension increases so the number of
nested braces will also increase.
Syntax:
array (
array (
array (elements...),
array (elements...),
...
),
array (
array (elements...),
array (elements...),
...
),
...
)

Example:
<?php
// PHP program to creating three
// dimensional array
// Create three nested array
$myarray = array(
array(
array(1, 2),
array(3, 4),
),
array(
array(5, 6),
array(7, 8),
),
);

// Display the array information


print_r($myarray);
?>

Output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
[1] => Array
(
[0] => Array
(
[0] => 5
[1] => 6
)
[1] => Array
(
[0] => 7
[1] => 8
)
)
)
Accessing multidimensional array elements: There are mainly two ways to
access multidimensional array elements in PHP.
 Elements can be accessed using dimensions as array_name[‘first
dimension’][‘second dimension’].
 Elements can be accessed using for loop.
 Elements can be accessed using for each loop.
Example:
<?php
// PHP code to create
// multidimensional array
// Creating multidimensional
// associative array
$marks = array(
// Ankit will act as key
"Ankit" => array(
// Subject and marks are
// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),
// Ram will act as key
"Ram" => array(
// Subject and marks are
// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),
// Anoop will act as key
"Anoop" => array(

// Subject and marks are


// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);
// Accessing the array element
// using dimensions
// It will display the marks of
// Ankit in C subject
echo $marks['Ankit']['C'] . "\n";
// Accessing array elements using for each loop
foreach($marks as $mark) {
echo $mark['C']. " ".$mark['DCO']." ".$mark['FOL']."\n";
}
?>

Output:
95
95 85 74
78 98 46
88 46 99
Iterating Multidimensional Array:
A multi-dimensional array in PHP is an array consists of one or more arrays. We
can access or retrieve the elements of a multi-dimensional array using
the foreach loop along with the for loop.
In the given example, we have used the nested foreach loop to iterate through
every element within the given multi-dimensional array.
<?php
$employees = array (array("Name" => "Harry", "Age" => 25, "Department" =>
"Management"), array("Name" => "Jack", "Age" => 31, "Department" =>
"Developer"), array("Name" => "Harry", "Age" => 35, "Department" =>
"Developer"));
foreach ($employees as $employee)
{
foreach ($employee as $key => $value)
{
echo "$value";
echo "<br>";
}
echo "<br>";
}
?>
Output

PHP File Handling:


File handling is needed for any application. For some tasks to be done file needs
to be processed. File handling in PHP is similar as file handling is done by using
any programming language like C. PHP has many functions to work with
normal files. Those functions are:
readfile() Function
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the server, that
looks like this:
The PHP code to read the file and write it to the output buffer is as follows
(the readfile() function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
Output:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The readfile() function is useful if all you want to do is open up a file and read
its contents.
1) fopen() – PHP fopen() function is used to open a file. First parameter of
fopen() contains name of the file which is to be opened and second parameter
tells about mode in which file needs to be opened, e.g.,

<?php
$file = fopen(“demo.txt”,'w');
?>

Files can be opened in any of the following modes :


 “w” – Opens a file for write only. If file not exist then new file is created
and if file already exists then contents of file is erased.
 “r” – File is opened for read only.
 “a” – File is opened for write only. File pointer points to end of file.
Existing data in file is preserved.
 “w+” – Opens file for read and write. If file not exist then new file is
created and if file already exists then contents of file is erased.
 “r+” – File is opened for read/write.
 “a+” – File is opened for write/read. File pointer points to end of file.
Existing data in file is preserved. If file is not there then new file is
created.
 “x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read
using fread(). It takes two arguments. One is file pointer and another is file size
in bytes, e.g.,

<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>

3) fwrite() – New file can be created or text can be appended to an existing file
using fwrite() function. Arguments for fwrite() function are file pointer and text
that is to written to file. It can contain optional third argument where length of
text to written is specified, e.g.,

<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>

4) fclose() – file is closed using fclose() function. Its argument is file which
needs to be closed, e.g.,

<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>

Reading from a file


 To read from a file it must be opened with fopen( ) first
 The feof( ) function can then be used to determine when the end of the
file has been reached.
 Returns true when the file pointer has reached the end of the file
 Each part of the input file can then be read with the fgets( ), fgetss( ),
or fgetcsv( ) functions.
fgets( resource fp, int length );
 Reads one line at a time from the file delimited by a new line character (\
n)
 $fp is the handle to the file to be read from
 999 means that 998 bytes will be read maximum before it stops reading
(1 byte for EOF)
fgetss( resource fp, int length, string [allowable_tags] );
 Automatically strips out any php or html tags that are not specifically
allowed
fgetcsv( resource fp, int length, [, string delimter [,
string enclosure] ] )
 Breaks up input lines based on the supplied delimiter
o Results are returned in an array
<?php
@ $fp = fopen( "guestbook.txt", "r" );
if( !$fp ) {
echo "The guestbook file could not be
opened.</body></html>";
exit;
}
?>
<table>
<!-- Simple read that puts entire line into a single row and cell -->
<?php
$line = fgets( $fp, 999 );
while( !feof( $fp ) ) {
echo "<tr><td>$line</td></tr>";
$line = fgets( $fp, 999 );
}
fclose( $fp );
?>
</table>
Reading the Whole File
o The readfile( ), fpasstatementru( ), and file( ) functions can be used
to read a files entire contents at once.
int readfile( string filename, [int include_use_path [, resource context ] ] )
 The readfile( ) function opens the file, echos the contents to standard
output (the browser), and then closes the file. It returns the number of
bytes read from the file.
boolean fpasstatementru( resource fp )
 Dumps files contents from the file pointer position to the end to standard
output.
int file( string filename )
 Same as readfile but instead of echoing content to standard out it turns the
content into an array.
Reading Single Characters
char fgetc( resource fp )
 Reads a single character at a time from the specified file.
 Will return the EOF character while the other read functions do not.
<?php
@ $fp = fopen( "guestbook.txt", "r" );
if( !$fp ) {
echo "The guestbook file could not be opened.</body></html>";
exit;
}
?>
<table>
<tr>
<th id="dateColumn">Date</th>
<th>Name</th>
<th>Email</th>
<th>Comment</th>
</tr>
<?php
$field = "";
$char = fgetc( $fp );
echo "<tr>";
while( !feof( $fp ) ) {
if( $char == "\t" ) {
echo "<td>$field</td>";
$field = "";
} elseif( $char == "\n" ) {
echo "<td>$field</td>";
$field = "";
echo "</tr>\n<tr>";
} else {
$field .= $char;
}
$char = fgetc( $fp );
}
?>
</table>
<a href="guestBookSign.php">Sign the Book Again</a>

Mouse events:

Event Event Description


Performed Handler

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over


the element

mouseout onmouseout When the cursor of the mouse leaves an


element

mousedown onmousedown When the mouse button is pressed over the


element

mouseup onmouseup When the mouse button is released over


the element
mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & onkeydown & When the user press and then release
Keyup onkeyup the key

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a


form element

Window/Document events
Event Event Description
Performed Handler

load onload When the browser finishes the loading of the


page

unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the


browser

You might also like