Web Complete
Web Complete
Web Complete
Tag Description
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
HTTP HTTPS
The full form of HTTP is the The full form of HTTPS is Hypertext Transfer
Hypertext Transfer Protocol. Protocol Secure.
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 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.
Tag Description
type="” Description
button Defines a simple push button, which can be programmed to perform a task on an
event.
HTML5 added new types on <input> element. Following is the list of types of elements
of HTML5.
datetime-local Defines an input field for entering a date without time zone.
month Defines a control with month and year, without time zone.
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.
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>
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>
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
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 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 />"; }
<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>
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 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.
<?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
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(
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
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),
),
);
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(
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 = fopen(“demo.txt”,'w');
?>
<?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);
?>
Mouse events:
Keyboard events:
Keydown & onkeydown & When the user press and then release
Keyup onkeyup the key
Form events:
Window/Document events
Event Event Description
Performed Handler
unload onunload When the visitor leaves the current webpage, the
browser unloads it