, , etc.), tables (, , ), lists (, , ), links (), inputs (, ), and forms (). It provides details on attributes like href, target, type, and examples of implementing each tag.">, , etc.), tables (, , ), lists (, , ), links (), inputs (, ), and forms (). It provides details on attributes like href, target, type, and examples of implementing each tag."> Address: [go: up one dir, main page] Include Form Remove Scripts Session Cookies Open navigation menuClose suggestionsSearchSearchenChange LanguageUploadSign inSign inDownload free for days0 ratings0% found this document useful (0 votes)27 views72 pagesWeb CompleteThe document defines various HTML tags for formatting text, creating lists, inserting links, and developing forms. It explains tags for text formatting (<i>, <small>, etc.), tables (<table>, <tr>, <td>), lists (<ul>, <ol>, <li>), links (<a>), inputs (<input>, <button>), and forms (<form>). It provides details on attributes like href, target, type, and examples of implementing each tag.Uploaded byRakshitha ManjunathAI-enhanced descriptionCopyright© © All Rights ReservedWe take content rights seriously. If you suspect this is your content, claim it here.Available FormatsDownload as DOCX, PDF, TXT or read online on ScribdDownloadSaveSave Web Complete For Later0%0% found this document useful, undefined0%, undefinedEmbedSharePrintReport0 ratings0% found this document useful (0 votes)27 views72 pagesWeb CompleteThe document defines various HTML tags for formatting text, creating lists, inserting links, and developing forms. It explains tags for text formatting (<i>, <small>, etc.), tables (<table>, <tr>, <td>), lists (<ul>, <ol>, <li>), links (<a>), inputs (<input>, <button>), and forms (<form>). It provides details on attributes like href, target, type, and examples of implementing each tag.Uploaded byRakshitha ManjunathAI-enhanced descriptionCopyright© © All Rights ReservedWe take content rights seriously. If you suspect this is your content, claim it here.Available FormatsDownload as DOCX, PDF, TXT or read online on ScribdCarousel PreviousCarousel NextDownloadSaveSave Web Complete For Later0%0% found this document useful, undefined0%, undefinedEmbedSharePrintReportDownload nowDownloadYou are on page 1/ 72SearchFullscreen.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 textHTML 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 captionHTML Table - Cell PaddingCell padding is the space between the cell edges and the cell content.By default, the padding is set to 0.HTML Table - Cell SpacingCell spacing is the space between each cell. By default, the space is set to 2 pixels.HTML Ordered ListIn the ordered HTML lists, all the list items are marked with numbers by default. It is knownas 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. OracleThe 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 RadishHTML Unordered ListIn HTML Unordered list, all the list items are marked with bullets. It is also known asbulleted 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 OracleThe 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 ListHTML Description list is also a list style which is supported by HTML and XHTML. It isalso 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 oranother 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 snacksLeo -It is also a one of the 12-horoscope sign.Oracle -It is a multinational technology corporation.Anchor tagThe <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 thelink'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 toThe name attribute can be used on the following elements: Elements Attribute <button> name <form> name <input> name <map> name <meta> name <textarea> nameHTML Links - The target AttributeBy 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 LinkTo 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 letthem 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> TagAn 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 processingsuch as name, email address, password, phone number, etc.HTML Form TagsLet'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> elementThe HTML <input> element is fundamental form element. It is used to create form fields, totake input from user. We can apply different input filed to gather different information formuser. 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 elementsof 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 ControlThe type="text" attribute of input tag creates textfield control also known as single linetextfield control. The name attribute is optional, but it is required for the server sidecomponent 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 formThe <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 FormIt is considered better to have label in form. As it makes the code parser/browser/userfriendly.If you click on the label tag, it will focus on the text control. To do so, you need to havefor 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 ControlThe 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 ControlThe email field in new in HTML 5. It validates the text for correct email address. Youmust 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 ControlThe 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 userclicks 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 buttonThe 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 attributeThe action attribute of <form> element defines the process to be performed on form whenform is submitted, or it is a URI to process the form information.The action attribute value defines the web page where information proceeds. It canbe .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 attributeThe 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=123unit-2Levels of Style SheetsThere are three levels of style sheets.• Inline - specified for a specific occurrence of a tag and apply only to that tag. This is finegrain 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 levelstyle sheet has precedence• For eg: if an external style sheet specifies a value for a particular property of a particulartag, that value is used until a different value is specified in either a document style sheet or aninline style sheet• Likewise, a document style sheet property value can be overridden by different propertyvalues 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 SyntaxThe 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 aresurrounded by curly braces.Inline CSSAn 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 ofthe <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 form2. Class selector3. Id selector4. Contexual Selectors5. Universal selector6. Pseudo classes1.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 valueis 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 namep.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 ofthe 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 bepresented in an especially noticeable style.</p>CLASSES• HTML and XHTML require each id be unique– therefore an idvalue can only be used once in a document.• You can mark a group of elements with a common identifierusing 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 inthedocument .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 descendantsof bold elements in the body of the document.It is also called as descendant selectors. It will not apply to emphasis element not descendantof bold face element.5.Universal Selectors• The universal selector denoted by an asterisk(*). It applies its style to all elements in thedocumentFor 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 targetelement(tag) simply exists. Names begin with colonsThe style of hover pseudo classes apply when the mouse cursor is over the element.The styleof focus pseudo classes apply when an element has focus (mouse cursor over the element andclick 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 • BordersProperty 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.JAVASCRIPTIt was introduced in the year 1995 for adding programs to the webpages in the NetscapeNavigator browserDisadvantages 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 VariableA JavaScript variable is simply a name of storage location. There are two types of variables inJavaScript: 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 TypesJavaScript provides different data types to hold different types of values. There are two typesof data types in JavaScript. Primitive data type Non-primitive (reference) data typeJavaScript is a dynamic type of language, means you don't need to specify type of thevariable because it is dynamically used by JavaScript engine. You need to use var here tospecify the data type. It can hold any type of values such as numbers, strings etc. Forexample:var a=40;//holding numbervar b="Rahul";//holding stringJavaScript primitive data typesThere 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 allJavaScript non-primitive data typesThe 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 expressionJavaScript Arithmetic OperatorsArithmetic operators are used to perform arithmetic operations on the operands. Thefollowing 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 = 9JavaScript Comparison OperatorsThe JavaScript comparison operator compares the two operands. The comparison operatorsare 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 = falseJavaScript Bitwise OperatorsThe bitwise operators perform bitwise operations on operands. The bitwise operators are asfollows: 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) = 2JavaScript Logical OperatorsThe 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) = trueJavaScript Assignment OperatorsThe 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 = 0JavaScript Special OperatorsThe 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-elseThe JavaScript if-else statement is used to execute the code whether condition is true orfalse. There are three forms of if statement in JavaScript. 1. If Statement 2. If else statementJavaScript If statementIt evaluates the content only if expression is true. The signature of JavaScript if statement isgiven below. if(expression){ //content to be evaluated }Flowchart of JavaScript If statementLet’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 statementLet’s see the example of if-else statement in JavaScript to find out the even or oddnumber.<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 loop1) JavaScript For loopThe JavaScript for loop iterates the elements for the fixed number of times. It should be usedif 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:123452) JavaScript while loopThe JavaScript while loop iterates the elements for the infinite number of times. Itshould be used if number of iteration is not known. The syntax of while loop is givenbelow.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:11121314153) JavaScript do while loopThe JavaScript do while loop iterates the elements for the infinite number of times likewhile loop. But, code is executed at least once whether condition is true or false. Thesyntax 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:2122232425JavaScript FunctionsA function (also known as a method) is a self-contained piece of code that performs aparticular "function". You can recognise a function by its format - it's a piece ofdescriptive text, followed by openand close brackets.A function is a reusable code-blockthat 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 scriptinto a function.A function contains code that will be executed by an event or by a call tothat function.You may call a function from anywhere within the page (or even from other pages if thefunction 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, itcould 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 afunction, it would havebeen executed as soon as the line was loaded. Now, the script isnot executed before the user hits the button. We have added an onClick event to thebutton that will execute the function displaymessage() when the button is clicked.How to Define a FunctionThe 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 thestart and end ofthe function.Note: A function with no parameters must include the parentheses () after the functionname:Note: Do not forget about the importance of capitals in JavaScript! The word functionmust be written inlowercase letters, otherwise a JavaScript error occurs! Also note thatyou must call a function with the exact same capitals as in the function name.The return StatementThe return statement is used to specify the value that is returned from thefunction.So, functions that are going to return a value must use thereturn statement.ExampleThe 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 variablecalled product.The Lifetime of JavaScript VariablesWhen you declare a variable within a function, the variable can only be accessed withinthat function. When you exit the function, the variable is destroyed. These variables arecalled local variables. You canhave local variables with the same name in differentfunctions, 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 isclosed.There are 3 types of pop-up boxes: Alert Confirm PromptThe alert method opens a dialog window and displays its parameter in that window. Italso 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 stringparameter, along with two buttons: OK and Cancel. confirm returns a Boolean value thatindicates the user’s button input: true for OK and false for Cancel. This method is oftenused 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 testthe variable, question, and react accordingly.The prompt method creates a dialog window that contains a text box used to collect astring 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.phpecho $_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 FunctionsPHP function is a piece of code that can be reused many times. It can take input as argumentlist 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 isdeclared. PHP variables can be one of four scope types − Local variables Function parameters Global variables Static variablesLocal VariablesA variable declared in a function is considered local; that is, it can be referenced solely in thatfunction. Any assignment outside of that function will be an entirely different variable fromthe 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 ParametersFunction parameters are declared after the function name and inside parentheses. They aredeclared much like a typical variable would be –<?php // multiply a value by 10 and return it to the callerfunction 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 100Global VariablesIn 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 inthe function in which it is to be modified. This is accomplished, conveniently enough, byplacing 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 variablehaving 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 16Static VariablesThe final type of variable scoping that I discuss is known as static. In contrast to the variablesdeclared as function parameters, which are destroyed on the function's exit, a static variablewill not lose its value when the function exits and will still hold that value should the functionbe called again. You can declare a variable to be static simply by placing the keywordSTATIC in front of the variable name.<?phpfunction keep_track(){ STATIC $count = 0;$count++;print $count; print "<br />"; }keep_track(); keep_track(); keep_track();?>This will produce the following result – 1 2 3PHP’s Superglobal VariablesPHP offers several useful predefined variables that are accessible from anywhere within theexecuting script and provide you with a substantial amount of environment-specificinformation. You can sift through these variables to retrieve details about the current usersession, the user’s operating environment, the local operating environment, and more. PHPcreates some of the variables, while the availability and value of many of the other variablesare specific to the operating system and web server. Therefore, rather than attempt toassemble 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 andthe script’s execution environment:foreach ($_SERVER as $var => $value){ echo "$var => $value <br />"; }Require () and include () in PHPPHP require () Function: The require () function in PHP is basically used to include thecontents/code/data of one PHP file to another PHP file. During this process if there are anykind of errors then this require () function will pop up a warning along with a fatal error andit 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 fileinto 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 thecontents/code/data of one PHP file to another PHP file. During this process if there are anykind 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 itsprocess. 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 seetwo 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 FunctionsThese functions allow interacting with and manipulating arrays in various ways. Arrays areessential 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 arrayPHP Calender FunctionsThe calendar extension presents a series of functions to simplify converting between differentcalendar 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 FunctionsThe functions provided by this extension check whether a character or string falls into acertain 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 FunctionsThese functions allow getting the date and timing from the server where PHP scripts arerunning. 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 FunctionsThese 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 FunctionsThese are functions dealing with error handling and logging. They allow user to define theirown error handling rules, as well as modify the way the errors can be logged. This allowsuser to change and enhance error reporting to suit their needs.Using these logging functions, user can send messages directly to other machines, to anemail, to system logs, etc. So user can selectively log and monitor the most important parts oftheir 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 FunctionPHP MySQLi functions gives to access the MySQLi database servers. PHP works withMySQLi 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 FunctionsThe file system functions are used to access and manipulate the file system. PHP provides allthe 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 FunctionsPHP 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 FunctionsPHP 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 ArrayAfter you've created an array, what about modifying it? No problem—you canmodify the values in arrays as easily as other variables. One way is to access anelement in an array simply by referring to it by index. For example, say youhave this array:$fruits[1] = "pineapple";$fruits[2] = "pomegranate";$fruits[3] = "tangerine";Now say you want to change the value of $fruits[2] to "watermelon". Noproblem 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 anew 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 shownin 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:watermelonOutput:3Removing Element from an Array:In order to remove an element from an array, we can use unset() function whichremoves the element from an array and then use array_values() function whichindexes 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. Theinformation 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 theelements 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 PortalConverting 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.Syntaxexplode(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 elementExample:<?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 arraysMulti-dimensional arrays are such type of arrays which stores another array ateach index instead of single element. In other words, define multi-dimensionalarrays as array of arrays. As the name suggests, every element in this array canbe an array and they can also hold other sub-arrays within. Arrays or sub-arraysin multidimensional arrays can be accessed using multiple dimensions.Dimensions: Dimensions of multidimensional array indicates the number ofindices needed to select an element. For a two-dimensional array two indices toselect an element.Two-dimensional array: It is the simplest form of a multidimensional array. Itcan be created using nested array. These types of arrays can be used to store anytype of elements, but the index is always a number. By default, the index startswith 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 indexedarray but instead of linear storage (indexed storage), every value can beassigned 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-dimensionalarrays. The difference is as the number of dimension increases so the number ofnested 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 toaccess 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:9595 85 7478 98 4688 46 99Iterating Multidimensional Array:A multi-dimensional array in PHP is an array consists of one or more arrays. Wecan access or retrieve the elements of a multi-dimensional array usingthe foreach loop along with the for loop.In the given example, we have used the nested foreach loop to iterate throughevery 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>";}?>OutputPHP File Handling:File handling is needed for any application. For some tasks to be done file needsto be processed. File handling in PHP is similar as file handling is done by usingany programming language like C. PHP has many functions to work withnormal files. Those functions are:readfile() FunctionThe 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, thatlooks 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<?phpecho readfile("webdictionary.txt");?>Output:AJAX = Asynchronous JavaScript and XMLCSS = Cascading Style SheetsHTML = Hyper Text Markup LanguagePHP = PHP Hypertext PreprocessorSQL = Structured Query LanguageSVG = Scalable Vector GraphicsXML = EXtensible Markup LanguageThe readfile() function is useful if all you want to do is open up a file and readits contents.1) fopen() – PHP fopen() function is used to open a file. First parameter offopen() contains name of the file which is to be opened and second parametertells 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 readusing fread(). It takes two arguments. One is file pointer and another is file sizein 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 fileusing fwrite() function. Arguments for fwrite() function are file pointer and textthat is to written to file. It can contain optional third argument where length oftext 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 whichneeds 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 allowedfgetcsv( 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 Characterschar 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 keyForm 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 elementWindow/Document eventsEvent Event DescriptionPerformed Handlerload onload When the browser finishes the loading of the pageunload onunload When the visitor leaves the current webpage, the browser unloads itresize onresize When the visitor resizes the window of the browserYou might also likeCH 6PDFNo ratings yetCH 652 pagesHTML CSS pdfPDFNo ratings yetHTML CSS pdf149 pagesUNIT 1 Introduction to HTMLPDFNo ratings yetUNIT 1 Introduction to HTML98 pagesHTML AS ITPDFNo ratings yetHTML AS IT84 pagesHTML Unit1PDFNo ratings yetHTML Unit164 pagesHTMLPDFNo ratings yetHTML69 pagesJ 6 PDFPDFNo ratings yetJ 6 PDF68 pagesHTML List and FormsPDFNo ratings yetHTML List and Forms18 pagesHTML CoursePDFNo ratings yetHTML Course73 pages1.1 Introduction to HTMLPDFNo ratings yet1.1 Introduction to HTML42 pagesBASIC-HTMLPDFNo ratings yetBASIC-HTML77 pagesHTML - Updated 25-8-20PDFNo ratings yetHTML - Updated 25-8-2043 pagesWeb Development Lec 3PDFNo ratings yetWeb Development Lec 328 pagesHTML GreatthoughtsITPDFNo ratings yetHTML GreatthoughtsIT37 pagesUnit 2PDFNo ratings yetUnit 210 pagesUnit-II Web TechPDFNo ratings yetUnit-II Web Tech55 pagesUnit Ii Web DesigningPDFNo ratings yetUnit Ii Web Designing55 pagesIntroto HTMLPDFNo ratings yetIntroto HTML23 pagesUnit-1PDFNo ratings yetUnit-1102 pagesLecture 03PDFNo ratings yetLecture 0328 pagesWhat Is HTML?: My First Heading My First ParagraphPDFNo ratings yetWhat Is HTML?: My First Heading My First Paragraph8 pagesBy Dinesh SharmaPDFNo ratings yetBy Dinesh Sharma35 pagesWT UNIT-1PDFNo ratings yetWT UNIT-115 pagesHTMLPDFNo ratings yetHTML44 pagesWP Unit-1PDFNo ratings yetWP Unit-147 pagesHTMLPDFNo ratings yetHTML59 pagesChapter 2 - HTML-elements and ListPDFNo ratings yetChapter 2 - HTML-elements and List10 pagesHTML ppt (1)PDFNo ratings yetHTML ppt (1)40 pagesWebpptPDFNo ratings yetWebppt19 pagesWeb Ass1PDFNo ratings yetWeb Ass116 pagesHTML FilePDFNo ratings yetHTML File10 pagesUNIT 1-OstPDFNo ratings yetUNIT 1-Ost25 pagesWhat is HTMLPDFNo ratings yetWhat is HTML29 pagesUnit 2 (Iwt)PDFNo ratings yetUnit 2 (Iwt)22 pagesThis A Heading This Is A Paragraph. This Is Another Paragraph.PDFNo ratings yetThis A Heading This Is A Paragraph. This Is Another Paragraph.4 pagesweb ppt[1]PDFNo ratings yetweb ppt[1]16 pagesChapter Three Part I and Part IIPDFNo ratings yetChapter Three Part I and Part II49 pagesWT Notes PSPPDFNo ratings yetWT Notes PSP50 pagesHTML Formatting: 1) Bold TextPDFNo ratings yetHTML Formatting: 1) Bold Text18 pagesChapter TwoPDFNo ratings yetChapter Two14 pagesHTMLPDFNo ratings yetHTML45 pagesHTML - Lists, Images and HyperlinksPDFNo ratings yetHTML - Lists, Images and Hyperlinks9 pagesInternet Programming (HTML)PDFNo ratings yetInternet Programming (HTML)36 pagesFront End - HTML, CSSPDFNo ratings yetFront End - HTML, CSS44 pagescsPDFNo ratings yetcs18 pagesClass - 10 HTML-1PDFNo ratings yetClass - 10 HTML-162 pagesWeb Technology Notes Part 2PDFNo ratings yetWeb Technology Notes Part 210 pagesHTML (BScCsit 5th Semester)PDFNo ratings yetHTML (BScCsit 5th Semester)59 pagesHTML FormsPDFNo ratings yetHTML Forms7 pagesjh_EcampusUpload_SubjectNote_4026f048-d810-4cfe-bfbb-5500c4fb315a_Grade_7_Ch_8_Advanced_features_of_HTMLPDFNo ratings yetjh_EcampusUpload_SubjectNote_4026f048-d810-4cfe-bfbb-5500c4fb315a_Grade_7_Ch_8_Advanced_features_of_HTML10 pagesTute 11 - Hypertext Markup LanguagePDFNo ratings yetTute 11 - Hypertext Markup Language16 pagesHTML - Basic TagsPDFNo ratings yetHTML - Basic Tags64 pagesWebTechnology Unit II NotesPDFNo ratings yetWebTechnology Unit II Notes16 pagesWhat is ListPDFNo ratings yetWhat is List6 pagesHTMLPDFNo ratings yetHTML7 pages1.notes - Intro To HTML-696PDFNo ratings yet1.notes - Intro To HTML-69618 pagesBasic of HTML: Name Enrollment NumberPDFNo ratings yetBasic of HTML: Name Enrollment Number29 pagesSome BestPDFNo ratings yetSome Best14 pagesArabic PDFPDFNo ratings yetArabic PDF855 pagesIntroduction To HTML HTML Stands For Hyper Text Markup Language. It Is A Formatting Language Used To DefinePDFNo ratings yetIntroduction To HTML HTML Stands For Hyper Text Markup Language. It Is A Formatting Language Used To Define7 pagesNcert Based Mcq for Upsc PDFPDFNo ratings yetNcert Based Mcq for Upsc PDF7 pagesRole of Clay Tower in Jet Fuel Processing - No PicturesPDFNo ratings yetRole of Clay Tower in Jet Fuel Processing - No Pictures68 pages8811 Chartof Accounts 6 TheditionelectronicversionPDFNo ratings yet8811 Chartof Accounts 6 Theditionelectronicversion127 pages4.5-7.0bcgb Technical Man PDFPDF100% (1)4.5-7.0bcgb Technical Man PDF86 pagesx 431 Pro Se说明书 enPDFNo ratings yetx 431 Pro Se说明书 en86 pagesDeveloping Policies, Protocols and ProceduresPDFNo ratings yetDeveloping Policies, Protocols and Procedures52 pagesCarrilloPDFNo ratings yetCarrillo48 pagesReference Theses For Oriental MindoroPDFNo ratings yetReference Theses For Oriental Mindoro13 pagesVehicle Loan Cum Hypothecation AgreementPDFNo ratings yetVehicle Loan Cum Hypothecation Agreement20 pagesPantone RGBPDF100% (1)Pantone RGB1 pageHow Bad Could a Second Trump Presidency GetPDFNo ratings yetHow Bad Could a Second Trump Presidency Get11 pagesQMS Unit1&2PDFNo ratings yetQMS Unit1&29 pagesLeith Mullings - Interrogating RacismPDFNo ratings yetLeith Mullings - Interrogating Racism32 pages2ND PRO12 OVERSIGHT MEETINGPDFNo ratings yet2ND PRO12 OVERSIGHT MEETING4 pagesMoral Neutralization in Pakistan Capital MarketsPDFNo ratings yetMoral Neutralization in Pakistan Capital Markets41 pagesOrder of Appointment Dermatology and Skin Cancer Center of South Carolina SignedPDFNo ratings yetOrder of Appointment Dermatology and Skin Cancer Center of South Carolina Signed4 pages13 AfPDFNo ratings yet13 Af10 pagesThe Impact of Trauma On Learning 909 311457 7PDFNo ratings yetThe Impact of Trauma On Learning 909 311457 76 pagesHeroidesPDFNo ratings yetHeroides2 pagesACTLIFE - SGS Inspection Booking Form - 872733PDFNo ratings yetACTLIFE - SGS Inspection Booking Form - 8727336 pagesBeowulf: His Three Great BattlesPDFNo ratings yetBeowulf: His Three Great Battles17 pagesArtisan Teacher OverviewPDFNo ratings yetArtisan Teacher Overview5 pagesLOGO DesignPDFNo ratings yetLOGO Design8 pagesKabir Admit CardPDFNo ratings yetKabir Admit Card3 pagesF2000 Check ListsPDFNo ratings yetF2000 Check Lists2 pagesPersonal Best A1 Unit 10 Reading TestPDFNo ratings yetPersonal Best A1 Unit 10 Reading Test3 pagesLicarios V GatmaitanPDFNo ratings yetLicarios V Gatmaitan16 pagesRelationships Between Urban Landscapes and Household PestsPDFNo ratings yetRelationships Between Urban Landscapes and Household Pests8 pagesMotion To Dismiss Statute of FraudPDFNo ratings yetMotion To Dismiss Statute of Fraud4 pagesEasy html and cssFrom EverandEasy html and cssS VASISTNo ratings yet
Web Complete
AI-enhanced description
Tag Description
Output:
Aries -One of the 12 horoscope sign.Bingo -One of my evening snacksLeo -It is also a one of the 12-horoscope sign.Oracle -It is a multinational technology corporation.
Anchor tagThe <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 thelink'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 toThe 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.
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 elementsof 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 ControlThe 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-2Levels of Style SheetsThere are three levels of style sheets.• Inline - specified for a specific occurrence of a tag and apply only to that tag. This is finegrain 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 levelstyle sheet has precedence• For eg: if an external style sheet specifies a value for a particular property of a particulartag, that value is used until a different value is specified in either a document style sheet or aninline style sheet• Likewise, a document style sheet property value can be overridden by different propertyvalues 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 SyntaxThe 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 aresurrounded by curly braces.
Inline CSSAn 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 ofthe <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 form2. Class selector3. Id selector4. Contexual Selectors5. Universal selector6. Pseudo classes1.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 valueis 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 namep.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 ofthe 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 bepresented in an especially noticeable style.</p>CLASSES• HTML and XHTML require each id be unique– therefore an idvalue can only be used once in a document.• You can mark a group of elements with a common identifierusing 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 inthedocument .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 descendantsof bold elements in the body of the document.It is also called as descendant selectors. It will not apply to emphasis element not descendantof bold face element.5.Universal Selectors• The universal selector denoted by an asterisk(*). It applies its style to all elements in thedocumentFor 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 targetelement(tag) simply exists. Names begin with colonsThe style of hover pseudo classes apply when the mouse cursor is over the element.The styleof focus pseudo classes apply when an element has focus (mouse cursor over the element andclick 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-elseThe JavaScript if-else statement is used to execute the code whether condition is true orfalse. There are three forms of if statement in JavaScript. 1. If Statement 2. If else statementJavaScript If statementIt evaluates the content only if expression is true. The signature of JavaScript if statement isgiven 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 oddnumber.<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 loop1) JavaScript For loopThe JavaScript for loop iterates the elements for the fixed number of times. It should be usedif 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:123452) JavaScript while loopThe JavaScript while loop iterates the elements for the infinite number of times. Itshould be used if number of iteration is not known. The syntax of while loop is givenbelow.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:11121314153) JavaScript do while loopThe JavaScript do while loop iterates the elements for the infinite number of times likewhile loop. But, code is executed at least once whether condition is true or false. Thesyntax 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:2122232425JavaScript FunctionsA function (also known as a method) is a self-contained piece of code that performs aparticular "function". You can recognise a function by its format - it's a piece ofdescriptive text, followed by openand close brackets.A function is a reusable code-blockthat 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 scriptinto a function.A function contains code that will be executed by an event or by a call tothat function.You may call a function from anywhere within the page (or even from other pages if thefunction 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, itcould 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 afunction, it would havebeen executed as soon as the line was loaded. Now, the script isnot executed before the user hits the button. We have added an onClick event to thebutton that will execute the function displaymessage() when the button is clicked.How to Define a FunctionThe 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 thestart and end ofthe function.Note: A function with no parameters must include the parentheses () after the functionname:Note: Do not forget about the importance of capitals in JavaScript! The word functionmust be written inlowercase letters, otherwise a JavaScript error occurs! Also note thatyou must call a function with the exact same capitals as in the function name.The return StatementThe return statement is used to specify the value that is returned from thefunction.So, functions that are going to return a value must use thereturn statement.ExampleThe 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 variablecalled product.The Lifetime of JavaScript VariablesWhen you declare a variable within a function, the variable can only be accessed withinthat function. When you exit the function, the variable is destroyed. These variables arecalled local variables. You canhave local variables with the same name in differentfunctions, 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 isclosed.There are 3 types of pop-up boxes: Alert Confirm PromptThe alert method opens a dialog window and displays its parameter in that window. Italso 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 stringparameter, along with two buttons: OK and Cancel. confirm returns a Boolean value thatindicates the user’s button input: true for OK and false for Cancel. This method is oftenused 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 testthe variable, question, and react accordingly.
The prompt method creates a dialog window that contains a text box used to collect astring 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.phpecho $_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 FunctionsPHP function is a piece of code that can be reused many times. It can take input as argumentlist 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 isdeclared. PHP variables can be one of four scope types − Local variables Function parameters Global variables Static variablesLocal VariablesA variable declared in a function is considered local; that is, it can be referenced solely in thatfunction. Any assignment outside of that function will be an entirely different variable fromthe 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 ParametersFunction parameters are declared after the function name and inside parentheses. They aredeclared much like a typical variable would be –<?php // multiply a value by 10 and return it to the callerfunction 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 100Global VariablesIn 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 inthe function in which it is to be modified. This is accomplished, conveniently enough, byplacing 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 variablehaving 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 16Static VariablesThe final type of variable scoping that I discuss is known as static. In contrast to the variablesdeclared as function parameters, which are destroyed on the function's exit, a static variablewill not lose its value when the function exits and will still hold that value should the functionbe called again. You can declare a variable to be static simply by placing the keywordSTATIC in front of the variable name.<?phpfunction keep_track(){ STATIC $count = 0;$count++;print $count; print "<br />"; }keep_track(); keep_track(); keep_track();?>This will produce the following result – 1 2 3PHP’s Superglobal VariablesPHP offers several useful predefined variables that are accessible from anywhere within theexecuting script and provide you with a substantial amount of environment-specificinformation. You can sift through these variables to retrieve details about the current usersession, the user’s operating environment, the local operating environment, and more. PHPcreates some of the variables, while the availability and value of many of the other variablesare specific to the operating system and web server. Therefore, rather than attempt toassemble 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 andthe 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> "; ?>
PHP include () Function: The include() function in PHP is basically used to include thecontents/code/data of one PHP file to another PHP file. During this process if there are anykind 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 itsprocess. 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 seetwo 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 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. Theinformation 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 theelements 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 PortalConverting 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.Syntaxexplode(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 arraysMulti-dimensional arrays are such type of arrays which stores another array ateach index instead of single element. In other words, define multi-dimensionalarrays as array of arrays. As the name suggests, every element in this array canbe an array and they can also hold other sub-arrays within. Arrays or sub-arraysin multidimensional arrays can be accessed using multiple dimensions.Dimensions: Dimensions of multidimensional array indicates the number ofindices needed to select an element. For a two-dimensional array two indices toselect an element.Two-dimensional array: It is the simplest form of a multidimensional array. Itcan be created using nested array. These types of arrays can be used to store anytype of elements, but the index is always a number. By default, the index startswith 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 indexedarray but instead of linear storage (indexed storage), every value can beassigned 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-dimensionalarrays. The difference is as the number of dimension increases so the number ofnested 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 toaccess 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:9595 85 7478 98 4688 46 99Iterating Multidimensional Array:A multi-dimensional array in PHP is an array consists of one or more arrays. Wecan access or retrieve the elements of a multi-dimensional array usingthe foreach loop along with the for loop.In the given example, we have used the nested foreach loop to iterate throughevery 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 fileusing fwrite() function. Arguments for fwrite() function are file pointer and textthat is to written to file. It can contain optional third argument where length oftext 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 whichneeds 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 eventsEvent Event DescriptionPerformed Handler
unload onunload When the visitor leaves the current webpage, the browser unloads it