Professional Documents
Culture Documents
Unit - III
JavaScript Vs Java
It is called strange object oriented programming language as it does not contain the class
and inheritance
Global Accessibility
● Being a scripting language, JavaScript cannot run on its own. In fact, the
browser is responsible for running JavaScript code.
● When a user requests an HTML page with JavaScript in it, the script is sent to the
browser and it is up to the browser to execute it.
● The main advantage of JavaScript is that all modern web browsers support
JavaScript.
● So, you do not have to worry whether your site visitor uses Internet Explorer,
Google Chrome, Firefox or any other browser. JavaScript will be supported.
● Also, JavaScript runs on any operating system including Windows, Linux or Mac.
Thus, JavaScript overcomes the main disadvantages of VBScript (Now deprecated)
which is limited to just IE and Windows.
● Java, JavaScript and Java are vastly different programming languages with different
uses.
● JavaScript is dynamically typed (also called weakly typed) in that variables can
be easily (or implicitly) converted from one data type to another.
● In a programming language such as Java, variables are statically typed, in that the
data type of a variable is defined by the programmer (e.g., int abc ) and enforced by
the compiler.
● With JavaScript, the type of data a variable can hold is assigned at runtime and
can change during run time as well.
Client-Side Scripting
The idea of client-side scripting is an important one in web development. It refers to the
client machine (i.e., the browser) running code locally rather than relying on the server to
execute code and return the result.
There are many client-side languages that have come into use over the past decade
including Flash, VBScript, Java, and JavaScript. Some of these technologies only work in
certain browsers, while others require plug-ins to function. We will focus on JavaScript due
to its browser interoperability (that is, its ability to work/operate on most browsers). Figure
6.1 illustrates how a client machine downloads and executes JavaScript code.
Refer to 6.2,6.3 and 6.4 also in text book
● Processing can be offloaded from the server to client machines, thereby reducing
the load on the server.
● The browser can respond more rapidly to user events than a request to a
remote server ever could, which improves the user experience.
● JavaScript can be linked to an HTML page in a number of ways. Just as CSS styles
can be inline, embedded, or external, JavaScript can be included in a number of
ways.
● Just as with CSS these can be combined, but external is the preferred method for
cleanliness and ease of maintenance.
Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly within
certain HTML attributes as
<html>
<body>
</body>
</html>
o/p
Embedded JavaScript
<html>
<head>
<script>
function msg() {
alert("I am executed through embedded javascript. I am a formal way ");
}
</script>
</head>
<body>
</body>
</html>
o/p
External JavaScript
It is often advantageous to separate the two into different files.
<!DOCTYPE html>
<html>
<head>
<script src="myscript.js"></script>
</head>
<body>
<h2>External JavaScript</h2>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
function myFunction()
{
alert("Hi!, I am exectuted from external file.");
}
o/p
Syntax in JavaScript
var name;
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br
/>");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
o/p
for loop
<html>
<head>
<script type="text/javascript">
function looping()
{
document.write("<h1>I am javascript</h1>");
var students = new Array("John", "Ann", "Aaron", "Edwin",
"Elizabeth");
document.write("<b>Using for loops </b><br />");
for (i=0;i<students.length;i++)
{
document.write((i+1)+" "+students[i] + "<br />");
}
}
</script>
</head>
<body>
<h1>I am html body</h1>
<input type=button onclick=looping() value="press me to show arrays">
</body>
</html>
o/p
Conditionals
if... else if
<html>
<head>
<script type="text/javascript">
function great2()
{
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one+ " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
}
</script>
</head>
<body>
<h1>Finding greater of two numbers using javascript</h1>
<input type=button onclick=great2() value="press me to find the greater of two numbers">
</body>
</html>
o/p
if inputs are 5 and 3, output is
5 is greater than 3
vowel.html
<<html>
<head>
<script>
function vowel()
{
var count = 0;
function countVowels(name)
{
for (var i=0;i<name.length;i++)
{
if(name[i].toLowerCase() == "a" || name[i].toLowerCase() == "e" ||
name[i].toLowerCase() == "i" || name[i].toLowerCase() == "o" || name[i].toLowerCase() ==
"u")
count = count + 1;
}
document.write("Hello," + name + "!!! Your name has " + count + " vowels.");
}
var myName = prompt("Please enter your name");
countVowels(myName);
}
</script>
</head>
<body>
Variables :
● Variables in JavaScript are dynamically typed, meaning a variable can be an
integer, float, and a string or an object. The data type of the variables is decided
during the execution time.
● This simplifies variable declarations, so that we do not require the familiar type
fields like int, char, and String.
● This syntax should be familiar to those who have programmed in languages like C
and Java.
Comparison Operators
Logical Operators
<body>
<p id="demo"></p>
<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 15) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
</html>
o/p
Loops
While Loops
The most basic loop is the while loop, which loops until the condition is not met.
var i=0;
while(i < 10){
//do something with i
i++;
}
For Loops
A for loop combines the common components of a loop: initialization, condition,
and post-loop operation into one statement.
Functions
They are defined by using the reserved word function and then the function name and
(optional) parameters.
Since JavaScript is dynamically typed, functions do not require a return type, nor do the
parameters require type.
Therefore a function to raise x to the yth power might be defined as:
function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
Alert
The alert() function makes the browser show a pop-up to the user, with whatever
is passed being the message displayed. The following JavaScript code displays a
simple hello world message in a pop-up:
alert ( "Good Morning" );
What is a DOM ?
JavaScript is almost always used to interact with the HTML document in which it is
contained. As such, there needs to be some way of programmatically accessing the
elements and attributes within the HTML. This is accomplished through a programming
interface (API) called the Document Object Model(DOM).
Document Object Model (DOM)
According to the W3C, the DOM is a:
JavaScript can access all the elements in a webpage making use of Document Object
Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is
loaded. The DOM model is created as a tree of objects like this:
DOM tree
Nodes
In the DOM, each element within the HTML document is called a node. If the DOM is a
tree, then each node is an individual branch. There are element nodes, text nodes, and
attribute nodes, as shown in Figure 6.18
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<script type="text/javascript">
o/p
DOM2-[(Identifying paragraphs through getElementsByTagName(“p”)]
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>This is getElementByTagName for accessing paragraphs</h1>
<p>Welcome to the first paragraph section</p>
<h2> This the second paragraph</h2>
<p id="second">This is the second paragraph section</p>
<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the FIRST paragraph is " + paragraphs[0].innerHTML);
alert("Content in the SECOND paragraph is " + paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The orginal message of second
paragraph is changed.";
</script>
</body>
</html>
o/p
DOM3( program for addEventListener without using onclick in input tag)
<html>
<head>
<title>DOM3 !!!</title>
</head>
<body>
<h3> This is an example program for addEventListener without using onclick in input
tag</h3>
<input type="button" id="btnClick" value="Click Me!!" />
<script type="text/javascript">
document.getElementById("btnClick").addEventListener("click", clicked);
function clicked()
{
alert("You clicked me. I have activated through addEventListener method!!!");
}
</script>
</body>
</html>
o/p
<!DOCTYPE html>
<html>
<body>
<button id="clickIt">Click here</button>
<b id="effect"></b>
<script>
const x = document.getElementById("clickIt");
const y = document.getElementById("hoverPara");
x.addEventListener("dblclick", RespondClick);
y.addEventListener("mouseover", RespondMouseOver);
y.addEventListener("mouseout", RespondMouseOut);
function RespondMouseOver() {
document.getElementById("effect").innerHTML +=
"MouseOver Event" + "<br>";
}
function RespondMouseOut() {
document.getElementById("effect").innerHTML +=
"MouseOut Event" + "<br>";
}
function RespondClick() {
document.getElementById("effect").innerHTML +=
"Click Event" + "<br>";
}
</script>
</body>
</html>
o/p
<html>
<body>
<p>Click the button to display the date.</p>
<table>
<tr><td>Press a key in the keyboard </td><td><button onkeydown="displayDate()">The
time is?</button></td></tr>
<tr><td>Double Click the mouse button</td> <td><button ondblclick="displayDate()">The
time is?</button></td></tr>
<tr><td>Move mouse down button</td><td><button onmousedown="displayDate()">The
time is?</button></td></tr>
<tr><td>Move mouse up button</td><td><button onmouseup="displayDate()">The time
is?</button></td></tr>
</table>
<script>
function displayDate() {
document.getElementById("demo").innerHTML += Date()+"<br>";
}
</script>
o/p
JavaScript Forms
Validation of forms
Name validation
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
o/p
Address validation
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["add1"].value;
var z = document.forms["myForm"]["add2"].value;
var l = document.forms["myForm"]["city"].value;
if (x == "" || y=="" || z=="" || l=="") {
alert("All data must be filled out");
return false;
}
else
alert("Congratulations! you have entered all the data intact");
}
</script>
</head>
<body>
</body>
o/p
<html>
<body>
<p>If the number is less than 100 or greater than 300, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
o/p
o/p
JavaScript design principles.
These principles increase the quality and reusability of the code while making it easier to
understand, and hence more maintainable.
Layers
● Perhaps the most common way of articulating such a cognitive model is via the
term layer. In object-oriented programming, a software layer is a way of
conceptually grouping programming classes that have similar functionality and
dependencies
Validation Layer
JavaScript can be also used to validate logical aspects of the user’s experience.
This could include, for example, validating a form to make sure the email entered is valid
before sending it along. It is often used in conjunction with the presentation layer
Asynchronous Layers
Normally, JavaScript operates in a synchronous manner where a request sent to the
server requires a response before the next lines of code can be executed. During the wait
between request and response the browser sits in a loading state and only updates
upon receiving the response.
In contrast, an asynchronous layer can route requests to the server in the background. In
this model, as certain events are triggered, the JavaScript sends the HTTP requests to the
server, but while waiting for the response, the rest of the application functions normally,
and the browser isn’t in a loading state.
When the response arrives JavaScript will (perhaps) update a portion of the page.
Asynchronous layers are considered advanced versions of the presentation and validation
layers above.
When the browser’s JavaScript engine encounters an error, it will throw an exception.
These exceptions interrupt the regular, sequential execution of the program and can stop
the JavaScript engine altogether. However, you can optionally catch these errors
preventing disruption of the program using the try–catch block as
try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}
JavaScript Objects
Array example
var greetings = new Array();
To initialize the array with values, the variable declaration would look like the
following:
Math
The Math class allows one to access common mathematic functions and common values
quickly in one place. This static class contains methods such as max() , min() , pow() ,
sqrt() , and exp() , and trigonometric functions such as sin() , cos() , and arctan() .
Math.PI
Math.sqrt(4);
Math.random();
// 3.141592657
// square root of 4 is 2.
// random number between 0 and 1
String
While one can use the new syntax to create a String object , it can also be defined using
quotes as follows:
Date
To display today’s date as a string, we would simply create a new object and use the
toString() method.
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>
<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>
o/p
5 Welcome
This is the welcome message
<html>.
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is the welcome message.</p>
<p >This is the technology section.</p>
<script type="text/javascript">
var paragraphs = document.getElementsByTagName("p");
alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
document.getElementById("second").innerHTML = "The orginal message is changed.";
</script>
</body>
</html>
Welcome
This is the welcome message.
5.1 Technology
This is the technology section.
JavaScript Events
The core of all JavaScript programming is the concept of an event.
A JavaScript event is an action that can be detected by JavaScript.
Many of them are initiated by user actions but some are generated by the browser itself.
Listener Approach
The problem with the inline handler approach is that it does not make use of layers; that
is, it does not separate content from behavior.
<html>
<body>
<p>This example uses the addEventListener() method to execute a function when a user
clicks anywhere in the document.</p>
<p id="demo">
<script>
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
o/p
This example uses the addEventListener() method to execute a function when a user
clicks anywhere in the document.
Hello World
Mouse Events
Mouse events are defined to capture a range of interactions driven by the mouse. These
can be further categorized as mouse click and mouse move events. Table 6.7 lists the
possible events one can listen for from the mouse.
<html>
<body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0"
src="rose.jpeg" alt="bouquet" width="32" height="32">
<p>The function bigImg() is triggered when the user moves the mouse pointer over the
image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of the
image.</p>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
</body>
</html>
o/p
Keyboard Events
Keyboard events are often overlooked by novice web developers, but are important
tools for power users. Table 6.8 lists the possible keyboard events.
o/p
onkeyup
<html>
<body>
<p>A function is triggered when the user releases a key in the input field. The function
transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
o/p
Form Events
Forms are the main means by which user input is collected and transmitted to the
server. Table 6.9 lists the different form events.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
<p>When you leave the input field, a function is triggered which transforms the input text
to upper case.</p>
</body>
</html>
o/p
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text
to upper case.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>
</body>
</html>
o/p
<!DOCTYPE html>
<html>
<head>
<script>
function message() {
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</form>
</body>
</html>
o/p
o/p
Onsubmit example program
<!DOCTYPE html>
<html>
<head>
<script>
function confirmInput() {
fname = document.forms[0].fname.value;
alert("Hello " + fname + "! You will now be redirected to www.aiet.org.in");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="https://www.aiet.org.in/">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>
o/p
Validate.html
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="vForm.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
vForm.html
<html>
<head>
<body>
<h1> you have successfully entered your name and your name</h1>
</body>
</html>
o/p
Validate1.html
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
Validate2.html
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["add1"].value;
var z = document.forms["myForm"]["add2"].value;
var l = document.forms["myForm"]["city"].value;
if (x == "" || y=="" || z=="" || l=="") {
alert("All data must be filled out");
return false;
}
else
alert("Congratulations! you have entered all the data intact");
}
</script>
</head>
<body>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
</br><tr><td>Name :</td> <td><input type="text" name="fname"></td> </tr>
</br><tr><td>Address :</td><td> <input type="text" name="add1"></td></tr>
</br><tr><td>Locality:</td> <td><input type="text" name="add2"></td></tr>
</br><tr><td>City :</td> <td><input type="text" name="city"></td></tr>
</br>
</br>
</br><tr> <td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
Validate3.html
<html>
<body>
<p>If the number is less than 100 or greater than 300, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
It is important to remember that when developing server-side scripts, you are writing
software, just like a C or Java programmer would do, with the major distinction that your
software runs on a web server and uses the HTTP request- response loop for most
interactions with the clients.
The fundamental difference between client and server scripts is that in a client-side script
the code is executed on the client browser, whereas in a server-side script, it is
executed on the web server.
● The most commonly used resource is data storage, often in the form of a
connection to a database management system. A database management system
(DBMS) is a software system for storing, retrieving and organizing large
amounts of data
Server-Side Technologies
ASP (Active Server Pages): This was Microsoft’s first server-side technology(also called
ASP Classic). Like PHP, ASP code (using the VBScript programminglanguage) can be
embedded within the HTML. ASP programming code is interpreted at run time, hence it
can be slow in comparison to other technologies.
ASP.NET: This replaced Microsoft’s older ASP technology. ASP.NET ispart of Microsoft’s
.NET Framework and can use any .NET programming language (though C# is the most
commonly used). ASP.NET uses an explicitly object-oriented approach and is often used
in larger corporate web application systems.
JSP (Java Server Pages) :JSP uses Java as its programming language and like
ASP.NET it uses an explicit object-oriented approach and is used in large enterprise web
systems and is integrated into the J2EE environment. Since JSP uses the Java Runtime
Engine, it also uses a JIT compiler for fast execution time and is cross-platform.
Node.js: This is a more recent server environment that uses JavaScript on the server
side, thus allowing developers already familiar with JavaScript to use just a single
language for both client-side and server-side development. Unlike the other development
technologies listed here, node.js is also its own web server software, thus eliminating the
need for Apache, IIS, or some other web server software.
Perl: Until the development and popularization of ASP, PHP, and JSP, Perl was the
language typically used for early server-side web development. As a language, it excels in
the manipulation of text. It was commonly used in conjunction with the Common Gateway
Interface (CGI), an early standard API for communication between applications and web
server software.
PHP: Like ASP, PHP is a dynamically typed language that can be embedded directly
within the HTML, though it now supports most common object-oriented features, such as
classes and inheritance. By default, PHP pages are compiled into an intermediary
representation called opcodes that are analogous to Java’s byte-code or the .NET
Framework’s MSIL. Originally, PHP stood for personal home pages, although it now is a
recursive acronym that means PHP: Hypertext Processor.
Python: This terse, object-oriented programming language has many uses, including
being used to create web applications. It is also used in a variety of web development
frameworks such as Django and Pyramid.
Ruby on Rails: This is a web development framework that uses the Ruby programming
language. Like ASP.NET and JSP, Ruby on Rails emphasizes the use of common software
development approaches, in particular the MVC design pattern.
In the multi-threaded mode, a smaller number of Apache processes are forked. Each of
the processes runs multiple threads. A thread is like a light- weight process that is
contained within an operating system process. A thread uses less memory than a process,
and typically threads share memory and code; as a consequence, the multi-threaded
mode typically scales better to large loads.
When using this mode, all modules running within Apache have to be thread- safe.
The syntax for loops, conditionals, and assignment is identical to JavaScript, only differing
when you getto functions, classes, and in how you define variables.
PHP Tags
The most important fact about PHP is that the code can be embedded directly within an
HTML file.
However, instead of having an .html extension, a PHP file will usually have the extension
.php.
Programming code must be contained within an opening <?php tag and a matching
closing ?> tag in order to differentiate it from the HTML.
The programming code within the <?php and the ?> tags is interpreted and executed,
while any code outside
the tags is echoed directly out to the client.
o/p
Welcome Randy
The server time is 12:58:50
<?php
# single-line comment
/*
This is a multiline comment.
They are a good way to document functions or complicated blocks of code
*/
$artist = readDatabase(); // end-of-line comment
?>
Variables, Data Types, and Constants : Variables in PHP are dynamically typed, which
means that you as a programmer do not have to declare the data type of a variable.
Instead the PHP engine makes a best guess as to the intended type based on what it is
being assigned. Variables are also loosely typed in that a variable can be assigned
different data types over time.
$count = 42;
Data types
<?php
$artist1="picasso";
$artist2="raphael";
$artist3="cezanne";
$artist4="rembrandt";
$artist5="giotto";
Program Control
Write example programs with explanation for the following constructs
if . . . else , switch . . . case, while(), for()
Include file;
It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement.
include "somefile.php"; # With include , a warning is displayed if not found and then
execution continues
include_once "somefile.php";
(include_once and require_once statements work just like include and require but if the
requested file has already been included once, then it will not be included again.)
menu.php
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
Main.php
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
o/p
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial
Functions : A set of self contained block of statements for executing some statements
repeatedly to improve the re usability in coding and save the memory space.
A function is a reusable piece or block of code that performs a specific action. Functions
can either return values when called or can simply perform an operation without returning
any value. PHP has over 700 functions built in that perform different tasks
In PHP there are two types of function: user-defined functions and built-in functions. A
user-defined function is one that you the programmer define. A built-in function is one of
the functions that come with the PHP environment
function functionName() {
code to be executed;
}
Function Syntax : calling
functionName()
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
O/P : Hello world!
5.2 PHP Functions with Parameters
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
// call by value
function addFive($num) {
$num += 5;
}
// call by reference
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "The Value after call by value is $orignum<br />";
addSix( $orignum );
echo " The Value after call by reference is $orignum<br />";
?>
</body>
</html>
o/p
The Value after call by value is 10
The Value after call by reference is 16