0% found this document useful (0 votes)
17 views

Web Dev Final Book Page Num

Uploaded by

aryanjsr432
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Web Dev Final Book Page Num

Uploaded by

aryanjsr432
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Index Object-based (DOM)

Event-based (SAX)
Chapter 1: XML

XML Introduction

1.1 XML Facts

1.2 XML Standards – an Overview

1.3 XML, DTD, and XML Schema

1.4 XML Schema

1.5 Declaration & Definition

1.6 XML Schema Reusability and


Conformance

1.7 Using XSL to Create HTML

XML Documents

Well-Formed XML Documents

Valid XML Documents

Components of XML Documents (DTD,


Schema, XSL)

XML Examples

Simple XML Documents

XML Documents with Attributes

XML Parsers

1
own document markups. It is a method
1.XML for putting structured data into a text
file; these files are easy to read,
unambiguous, extensible, and platform-
independent.

1.1 XML Facts XML is a family of technologies that


includes XML 1.1, Xlink, Xpointer,
XML is officially recommended by XPath, CSS, XSL, XSLT, XML DOM,
W3C since 1998 and is a simplified XML Namespaces, and XML Schemas.
form of SGML (Standard Generalized
Markup Language). It was primarily
created by Jon Bosak of Sun
The Difference Between XML and
Microsystems. Hypertext markup
HTML
language was configured for showing
data, while XML was designed to hold XML is not a replacement for HTML.
data. It's utilized to send and store XML and HTML were designed with
information with a focus on what data different goals: HTML was designed to
comprises. XML is highly required for display data, focusing on how data
publishers, technical, informative, looks, while XML was designed to
commercial, media, financial, legal transport and store data, focusing on
firms, and additional business sectors. what data is.

What is XML? Quick Comparison

XML stands for EXtensible Markup HTML uses tags and attributes; content
Language. It is a markup language and formatting can be placed together,
much like HTML and was designed to such as
carry data, not to display data. XML <p><font="Arial">text</font>, with
tags are not predefined; users must predetermined and rigid tags and
define their own tags. XML is designed attributes. In contrast, XML uses tags
to be self-descriptive and is a W3C and attributes where content and
Recommendation. format are separate; formatting is
contained in a stylesheet, allowing
users to specify what each tag and
What is XML? attribute means.

XML serves as a meta-language that


allows users to create and format their
1.2 XML Standards – an Overview
2
The XML Core Working Group </root>
produced XML 1.0 (Feb 1998) and
A Simple XML Document
XML 1.1 (candidate for
recommendation). XML Namespaces xml
were established in Jan 1999. The
XSLT Working Group introduced XSL Copy code
Transformations 1.0 (Nov 1999) and <?xml version="1.0"?>
XPath 1.0 (Nov 1999). The eXtensible
Stylesheet Language XSL(-FO) 1.0 was <Book>
published in Oct 2001. The XML <author>Ditel & Ditel</author>
Linking Working Group created XLink
1.0 (Jun 2001) and XPointer 1.0 <title>Internet and World Wide
(March 2003, 3 substandards). XQuery Web</title>
1.0 was released in Nov 2002, along
<price>850</price>
with many substandards, and XML
Schema 1.0 was introduced in May </Book>
2001.
This document contains freely
definable tags and processing
instructions.
XML Documents

An XML document contains elements


and attributes. XML documents must A Simple XML Document with
contain a root element, which serves as Attributes
the parent of all other elements. The
Attributes can have names and values,
elements in an XML document form a
as shown below:
document tree that starts at the root
and branches to the lowest level. All
elements can have sub-elements (child
elements), for example: xml

<article>

xml <author>Gerhard
Weikum</author>
<root>
<title>The Web in Ten Years</title>
<child>
<text>In order to evolve</text>
<subchild>.....</subchild>
</article>
</child>
3
XML Components There are no isolated markup
characters in the text (i.e., < > & ]]>).
There are four components for XML
content: the XML document, DTD If there is no DTD, all attributes are of
(Document Type Declaration), XML type CDATA by default.
Schema, and XSL (Extensible
A Valid XML Document
Stylesheet Language). The DTD,
schema, and XSL do not need to be A valid XML document has an
present in all cases. associated DTD and schema and
complies with the constraints in the
DTD and schema.
Types of XML Document

Well-Formed XML Document


XML Basics
A well-formed document in XML is a
The XML declaration (<?xml>) is not
document that adheres to the syntax
required but is typically used.
rules specified by the XML
Attributes include:
specification, satisfying both physical
and logical structures. version

encoding – the character encoding


used in the document
Valid XML Document
standalone – if an external DTD is
An XML document validated against a
required
DTD and XML Schema is "Well
Formed" and "Valid." Examples:

xml
A Well-formed XML Document <?xml version="1.0" encoding="UTF-
8"?>
Elements have an open and close tag
unless it is an empty element. <?xml version="1.0"
standalone="yes"?>
Attribute values are quoted.
XML Basics
If a tag is an empty element, it has a
closing / before the end of the tag. To specify a DTD for the document,
use:
Open and close tags are nested
correctly. xml

4
<!DOCTYPE …> Namespaces

There are two forms: Namespaces are not mandatory but are
useful in giving uniqueness to an
xml
element. They help avoid element
<!DOCTYPE root-element SYSTEM collision and are declared using the
"URIofDTD"> xmlns:name=value attribute; a URI is
recommended for the value.
<!DOCTYPE root-element PUBLIC Namespaces can be an attribute of any
"name" "URIofDTD"> element, and their scope is inside the
XML Basics element’s tags.

Comments are defined as follows: XML Basics

xml To define special sections of character


data that the processor does not
<!-- --> interpret as markup, use:
The contents are ignored by the xml
processor, cannot come before the
XML declaration, and cannot appear <![CDATA[ ]]>
inside an element tag. Anything inside is treated as plain text.

XML Advantages (1)


XML Basics XML separates data from HTML.
An element is defined as follows: XML simplifies data sharing.
xml XML simplifies data transport.
<tag> text </tag> XML simplifies platform changes.
It can contain text, other elements, or a XML makes your data more available.
combination. The element name must
start with a letter or underscore and XML is used to create new Internet
can have any number of letters, languages.
numbers, hyphens, periods, or
XML Advantages (2)
underscores. Element names are case-
sensitive and may not start with "xml." XML is important because it removes
two constraints that were holding back
web developments:
XML Basics

5
Dependence on a single, inflexible A valid document conforms to the
document type (HTML). regular-expression grammar.

The complexity of full SGML, whose The attribute types must be correct.
syntax allows many powerful but hard-
The constraints on references must be
to-program options.
satisfied.

Document Type Definitions (DTDs)


1.3 XML, DTD, and XML Schema
DTD: Document Type Definition; a
XML Validation way to specify the structure of XML
documents.
XML with correct syntax is referred to
as "Well Formed" XML. A DTD adds syntactical requirements
in addition to the well-formed
XML validated against a DTD
requirement.
(Document Type Definition) or XML
Schema is called "Valid" XML. DTDs help:

Well-Formed XML Documents Eliminate errors when creating or


editing XML documents.
A "Well Formed" XML document
adheres to the correct XML syntax. The Clarify the intended semantics.
syntax rules include:
Simplify the processing of XML
XML documents must have a root documents.
element.
Uses a regular expression-like syntax
XML elements must have a closing tag. to specify the grammar for the XML
document.
XML tags are case sensitive.
Limitations include:
XML elements must be properly nested.
Weak data types.
XML attribute values must be quoted.
Inability to specify constraints.
Valid XML Documents
No support for schema evolution.
A "Valid" XML document is a "Well
Formed" XML document that conforms Example: An Address Book
to the rules specified in a Document
xml
Type Definition (DTD):
<person>

6
<name>Homer Simpson</name> xml
<!-- Exactly one name -->
<?xml version="1.0"?>
<greet>Dr. H. Simpson</greet> <!-
<!DOCTYPE db [<!ELEMENT ...> …
- At most one greeting -->
]>
<addr>1234 Springwater
<db> ... </db>
Road</addr> <!-- As many address
lines as needed (in order) --> A DTD from the local file system:
<addr>Springfield USA, xml
98765</addr>
<!DOCTYPE db SYSTEM
<tel>(321) 786 2543</tel> <!-- "schema.dtd">
Mixed telephones and faxes -->
A DTD from a remote file system:
<fax>(321) 786 2544</fax>
xml
<tel>(321) 786 2544</tel>
<!DOCTYPE db SYSTEM
"http://www.schemaauthority.com/sche
<email>[email protected] ma.dtd">
</email> <!-- As many as needed -->
Specifying the Structure
</person>
name
Adding a DTD to the Document
greet?
A DTD can be:
name, greet?
Internal: The DTD is part of the
document file. addr*

External: The DTD and the document tel | fax


are in separate files. a name element
An external DTD may reside: an optional (0 or 1) greet element
In the local file system (where the a name followed by an optional greet
document is).
to specify 0 or more address lines
In a remote file system.
a tel or a fax element
Connecting a Document with its DTD
(tel | fax)*: 0 or more repeats of tel or
An internal DTD: fax

7
email*: 0 or more email elements Inside the group, no regular
expressions are allowed—only element
Full Structure of a Person Entry
names.
The whole structure is specified by:
#PCDATA must be first, followed by 0
name, greet?, addr*, (tel | fax)*, email* or more element names, separated by |.

Regular expression syntax is used to The group can be repeated 0 or more


describe each element type in the times.
XML document.
Address-Book Document with an
Each attribute of an element type is Internal DTD
described in the DTD by enumerating
xml
its properties (OPTIONAL, etc.).
Copy code
Element Type Definition
<?xml version="1.0" encoding="UTF-
For each element type E, a declaration
8"?>
is formed:
<!DOCTYPE addressbook [
xml
<!ELEMENT addressbook
<!ELEMENT E content-model>
(person*)>
Where the content-model can be:
<!ELEMENT person (name, greet?,
EMPTY: Element has no content. address*, (fax | tel)*, email*)>

ANY: Content can be any mixture of <!ELEMENT name (#PCDATA)>


PCDATA and elements defined in the
<!ELEMENT greet (#PCDATA)>
DTD.
<!ELEMENT address (#PCDATA)>
(#PCDATA): Parsed character data.
<!ELEMENT tel (#PCDATA)>
The Definition of Mixed Content
<!ELEMENT fax (#PCDATA)>
Mixed content is described by a
repeatable OR group: <!ELEMENT email (#PCDATA)>

]>

xml The Rest of the Address-Book


Document
(#PCDATA | element-name | …)*
xml

8
<addressbook> The accuracy attribute is optional.

<person> CDATA is the “type” of the attribute –


character data.
<name>Jeff Cohen</name>
The Format of an Attribute Definition
<greet>Dr. Cohen</greet>
<!ATTLIST element-name attr-name
<email>[email protected]</email>
attr-type
</person>
attr-default>
</addressbook>
➢ The default value is given inside
Some Difficult Structures quotes

Each employee element should contain ➢ Attribute types:


name, age, and ssn elements in some
order: ➢ CDATA

xml ➢ ID, IDREF, IDREFS

<!ELEMENT employee ➢ ID, IDREF, IDREFS are used for


((name, age, ssn) | (age, ssn, name) | references
(ssn, name, age) | ...) ➢ Attribute Default
>
➢ #REQUIRED: the attribute must be
This may lead to too many explicitly provided
permutations!
➢ #IMPLIED: attribute is optional, no
Attribute Specification in DTDs default provided
xml ➢ "value": if not explicitly provided,
<!ELEMENT height (#PCDATA)> this value inserted by default

<!ATTLIST height ➢ #FIXED "value": as above, but only


this value is allowed
dimension CDATA #REQUIRED
1.4 XML Schema
accuracy CDATA #IMPLIED
What is XML Schema?
>
• The origin of schema
The dimension attribute is required.

9
▪ XML Schema documents are used to Limitations of DTD
define and
• No constraints on character
validate the content and structure of
data
XML data.
• Not using XML syntax
▪ XML Schema was originally
proposed by Microsoft, • No support for namespace
but became an official W3C • Very limited for reusability and
recommendation in May
extensibility
2001
Advantages of Schema
Why Schema? (1)
• Syntax in XML Style
•Information
• Supporting Namespace and
•Structure
import/include
•Format
• More data types
•Traditional Document:
• Able to create complex data type by
•Everything is clumped together
inheritance
•Information
• Inheritance by extension or
•Structure restriction
•Format XML Schema
•“Fashionable” Document: A An XML Schema:
document
• defines elements that can appear in a
is broken into discrete parts, which document
can be treated separately • defines attributes that can appear
within elements
•Separating Information from
Structure and Format • defines which elements are child
elements
Why Schema? (2)
• defines the sequence in which the
•Schema Workflow
child elements can appear
DTD versus Schema
• defines the number of child elements

10
• defines whether an element is empty 13 Kinds of Schema Components
or can include text
• Simple type definitions
• defines default values for attributes
• Complex type definitions
The purpose of a Schema is to define
• Attribute declarations
the legal building blocks of an
• Element declarations
XML document, just like a DTD.
• Attribute group definitions
XML Schema – Better than DTDs
• Identity-constraint definitions
XML Schemas
• Model group definitions
➢ are easier to learn than DTD
• Notation declarations
➢ are extensible to future additions
◼ Annotations
➢ are richer and more useful than
DTDs ◼ Model groups

◼ Particles
➢ are written in XML
◼ Wildcards
➢ support data types
◼ Attribute Uses
XML Schema Components
•XML Schema
◼Abstract Data Model
•(.xsd)
◼ Simple and Complex Type
Definitions XML document & XML Schema

◼ Declarations •Information

XML Abstract Data Model •Items

• The XML Abstract Data Model– •…


composes of Schema Components.– is
•Elements
used to describe XML Schemas.
•Attributes
• Schema Component– is the generic
term for the building blocks that •Declaration

compose the abstract data model of the •Type Definition


schema.
•XML Document

11
•(.xml) • Example

1.5 Declaration & Definition •<xs:simpleType


name="farenheitWaterTemp">
• Declaration Components– are
associated by (qualified) names to • <xs:restriction base="xs:number">

information items being validated.– It • <xs:fractionDigits value="2"/>


is like declaring objects in OOP.
• <xs:minExclusive value="0.00"/>
• Definition Components– define
• <xs:maxExclusive value="100.00"/>
internal schema components that can
be • </xs:restriction>
used in other schema components. – •</xs:simpleType>
Type definition is like defining classes
in OOP. •

Type Definitions Complex Type Definition

• Why Type Definitions? • Inheritance

• Simple Type Definition VS. Complex Each complex type definition is either
Type Definition – a restriction of a complex type
definition– an extension of a simple or
•Simple Type complex type definition– a restriction
of the ur-type definition.
•Definition
• Example
•Complex Type
•<xs:complexType
• Attributes & Elements
name="personName">
without element children
• <xs:sequence>
•Definition
• <xs:element name="title"
• Elements
minOccurs="0"/>
Simple Type Definition
•… …
• Simple Type Definition can be:– a
• </xs:sequence>
restriction of some other simple type;–
a list or union of simple type •</xs:complexType>
definition;or– a built-in primitive
datatypes.

12
•<xs:complexType <xs:complexType>
name="extendedName">
<xs:sequence>
• <xs:complexContent>
<xs:element name="title"
• <xs:extension base="personName"> type="xs:string"/>

• <xs:sequence> <xs:element name="author"


type="xs:string"/>
• <xs:element name="generation"
<xs:element name=“qualification“

type=“xs:string”/>
• </xs:sequence>
</xs:sequence>
• </xs:extension>
</xs:complexType>
minOccurs="0"/>
</xs:element>
• </xs:complexContent>
</xs:schema>
•</xs:complexType>
•book.xsd
An XML Instance Document Example
1.6 XML Schema
<book ISBN = "0836">
Reusability and Conformance
<title> INTERNET AND WORLD
◼ XML Schema Reusability
WIDE WEB</title>
◼ XML Schema Conformance
<author>Charles M</author>
Building Reusable XML Schema
<qualification> Extroverted beagle
</qualification> • Two mechanisms– Including and
Redefining existing XML
</book>
Schemas components in an XML
The Example’s Schema
Schema
<?xml version="1.0" encoding="utf-
definition– Extending or Restricting
8"?>
existing data types in
<xs:schema
an XML Schema definition
xmlns:xs="http://www.w3.org/2001/X
MLSchema"> Building Reusable XML Schema- (1)

<xs:element name="book">

13
• xs:include– Similar to a copy and • <xs:sequence>
paste
• <xs:element name="to"
of the included schema– The calling type="xs:string"/>
schema doesn't
• <xs:element name="from"
allow to override the type="xs:string"/>

definitions of the included • <xs:element name="heading"


type="xs:string"/>
schema.
• </xs:sequence>
• xs:redefine– Similar to xs:include–
except that it lets you • <xs:element name="body"
type="xs:string"/>
redefine declarations from
• <xs:attribute name=“timestamp”
the included schema.
type=“xs:date” />
Conformance Example: note.xml and
• </xs:complexType>
note.xsd
•</xs:element>
•<?xml version="1.0"? >
•</xs:schema>
•<note timestamp=“2002-12-20”>
XML Parsers
• <to>Dove</to>
• Every XML application is based on a
• <from>Jani</from>
parser
• <heading>Reminder</heading>
• Two types of XML documents:– Well-
• <body>Don't forget me this formed:if it obeys the syntax of XML –
weekend!</body> Valid:if it conforms to a proper
definition of legal
•</note>
structure and elements of an XML
•<?xml version="1.0"?> document
•<xs:schema • Two types of XML Parsers:– Non-
xmlns:xs="http://www.w3.org/2001/X validating– Validating
MLSchema" >
Two Ways of Interfacing XML
•<xs:element name="note"> Documents with
• <xs:complexType> XML Applications

14
• Object-based: DOM •What is XML Software Development

(Document Object process?

Model)– Specified by W3C– Tree is 1. Begin with developing content


built– The parser loads the model using XML

XML doc into computer Schema or DTD

memory and builds a tree 2. Edit and validate XML documents


according to the content
of objects for all elements
model
& attributes
3. Finally, the XML document is ready
• Event-based: SAX (Simple
to be used or processed by
API for XML)– Originally a Java-only
an XML enabled framework
API. – Developed by XML-DEV
What is XML Software Development
mailing list community– No tree is
built– The parser reads the file process?

and triggers events as it •The xml software development process

finds elements/attribute/text •Xml schema enable translations from


XML documents to
in the XML doc
databases.
Available XML Schema-supported
Parsers XML Integrated Development
Environments
• Apache® Xerces 2 Java/C++ free–
Validating/Non-validating – DOM and (IDE) -1
SAX
•WEB
• Microsoft® XML Parser 4.0 free–
DEVELOPMENT
DOM and SAX
TOOLS
• TIBCO® XML Validate commercial–
SAX-based implementation •Java
• SourceForge.net® JBind 1.0 free– A programming
data binding framework linking Java
and XML tools

• And many many more… •Data base

15
•Programming they can be displayed)

•Microsoft Visual ◼ XPath is a language to select parts


of an XML document to transform
studio
with XSLT
•.NET • XML
◼ XSL-FO (XSL Formatting Objects)
IDE
is a replacement for CSS
•XML IDE provides comprehensive
◼ There are no current
XML
implementations of XSL-FO, and we
development support and complements won’t cover it

other software development tools How does it work?

◼ The XML source document is


parsed into an XML
XSL
source tree
eXtensible Stylesheet Language
◼ You use XPath to define templates
XSLT
that match parts of
What is XSL?
the source tree
◼ XSL stands for Extensible Stylesheet
◼ You use XSLT to transform the
Language
matched part and put
◼ CSS was designed for styling HTML
the transformed information into the
pages, and can be used to
result tree
style XML pages
◼ The result tree is output as a result
◼ XSL was designed specifically to document
style XML pages, and is
◼ Parts of the source document that
much more sophisticated than CSS are not matched by a

◼ XSL consists of three languages: template are typically copied


unchanged
◼ XSLT (XSL Transformations) is a
language used to transform XML Simple XPath

documents into other kinds of ◼ Here’s a simple XML document:


documents (most commonly HTML, so
<?xml version="1.0"?>

16
<library> ◼ <xsl:for-each select="//book">
loops through every
<book>
book element, everywhere in the
<title>XML</title>
document
<author>Gregory Brill</author>
◼ <xsl:value-of select="title"/>
</book> chooses the content of

<book> the title element at the current location

<title>Java and XML</title> ◼ <xsl:for-each select="//book">

<author>Brett McLaughlin</author> <xsl:value-of select="title"/>

</book> </xsl:for-each>

</library > chooses the content of the title element


for each book in the XML document
◼ XPath expressions look
1.7 Using XSL to create HTML
a lot like paths in a
◼ Our goal is to turn this:
computer file system
<?xml version="1.0"?>
◼ / means the document
<library>
itself (but no specific
<book>
elements)
<title>XML</title>
◼ /library selects the root
<author>Gregory Brill</author>
element
</book>
◼ /library/book selects
<book>
every book element
<title>Java and XML</title>
◼ //author selects every
◼ Into HTML that displays
author element,
something like this:
wherever it occurs
Book Titles:
Simple XSLT
• XML

17
• Java and XML ◼ <?xml version="1.0"?>

Book Authors: <?xml-stylesheet type="text/xsl"


href="books.xsl"?>
<author>Brett McLaughlin</author>
<library>
</book>
<book>
</library >
<title>XML</title>
• Gregory Brill
<author>Gregory Brill</author>
• Brett McLaughlin
</book>
▪ Note that we’ve grouped
<book>
titles and authors
<title>Java and XML</title>
separately
<author>Brett McLaughlin</author>
What we need to do
</book>
◼ We need to save our XML into a file
(let’s call it </library >

books.xml) This tells you where

◼ We need to create a file (say, to find the XSL file


books.xsl) that describes
Desired HTML
how to select elements from books.xml
<html>
and embed
<head>
them into an HTML page
<title>Book Titles and
◼ We do this by intermixing the
Authors</title>
HTML and the XSL in the
</head>
books.xsl file
<body>
◼ We need to add a line to our
books.xml file to tell it to <h2>Book titles:</h2>

refer to books.xsl for formatting <ul>


information
<li>XML</li>
books.xml, revised
<li>Java and XML</li>

18
</ul> <xsl:for-each select="//book">

<h2>Book authors:</h2> <li>

<ul> <xsl:value-of select="title"/>

<li>Gregory Brill</li> </li>

<li>Brett McLaughlin</li> </xsl:for-each>

</ul> </ul>

</body> <h2>Book authors:</h2>

</html> ...same thing, replacing title with


author
Blue text is data extracted from the
XML document Notice the

Brown text is our HTML template xsl:for-each

We don’t necessarily loop

know how much data ▪ Notice that XSL can rearrange the
data; the HTML result can present
we will have
information in a different order than
XSL outline the XML

<?xml version="1.0" encoding="ISO- All of books.xml


8859-1"?>
◼ <?xml version="1.0"?>
<xsl:stylesheet version="1.0"
<?xml-stylesheet type="text/xsl"
xmlns:xsl="http://www.w3.org/1999/X href="books.xsl"?>
SL/Transform">
<library>
<xsl:template match="/">
<book>
<html> ... </html>
<title>XML</title>
</xsl:template>
<author>Gregory Brill</author>
</xsl:stylesheet>
</book>
<h2>Book titles:</h2>
<book>
<ul>
<title>Java and XML</title>

19
<author>Brett McLaughlin</author> </xsl:for-each>

</book> </ul>

</library > <h2>Book authors:</h2>

Note: if you do View Source, <ul>

this is what you will see, not the <xsl:for-each

resultant HTML select="//book">

All of books.xsl <li>

<?xml version="1.0" encoding="ISO- <xsl:value-of


8859-1"?>
select="author"/>
<xsl:stylesheet version="1.0"
</li>

</xsl:for-each>
xmlns:xsl="http://www.w3.org/1999/
</ul>
XSL/Transform">
</body>
<xsl:template match="/">
</html>
<html>
</xsl:template>
<head>
</xsl:stylesheet>
<title>Book Titles and
Authors</title> How to use it
</head> ◼ In a modern browser you can just
open the XML
<body>
file
<h2>Book titles:</h2>
◼ Older browsers will ignore the XSL
<ul>
and just show you
<xsl:for-each select="//book">
the XML contents as continuous text
<li>
◼ You can use a program such as
<xsl:value-of select="title"/> Xalan, MSXML,

</li> or Saxon to create the HTML as a file

20
◼ This can be done on the server side,
so that all the client

side browser sees is plain HTML

◼ The server can create the HTML


dynamically from the

information currently in XML

21
Index String Functions

strlen()
Chapter 2: PHP
str_replace()
Array Functions
strpos()
2.1 array_chunk
substr()
2.2 array_change_key_case

2.3 array_combine
Server-Side Basics
2.4 array_count_values
URL Structure and Web Servers
2.5 array_diff_assoc
PHP Basics (Syntax, Variables, and
2.6 array_diff_key Data Types)

2.7 array_diff Control Structures (if-else)

2.8 array_intersect

PHP Functions

Defining Functions

Returning Values from Functions

Function Parameters

GET and POST Methods

The GET Method

The POST Method

$_REQUEST Variable

PHP Form Handling

Form Input Validation

Processing Form Data

22
array_change_key_case()
2. PHP • The array_change_key_case()
function changes

all keys in an array to lowercase or


uppercase.
ARRAY FUNCTIONS
• Syntax
2.1 array_chunk
• array_change_key_case(array,case);
Syntax
Parameter
array array_chunk ( array $input , int
$size [, bool • array Required. Specifies the array to
use
$preserve_keys = false ] )
• case Optional. Possible values:
Description
CASE_LOWER - Default value.
Chunks an array into size large
Changes the keys
chunks. The last chunk
to lowercase
may contain less than size elements.
CASE_UPPER - Changes the keys to
Example
uppercase
<?php
• <?php
$input_array = array('a', 'b', 'c', 'd',
'e');
$age=array("Peter"=>"35","Ben"=>"
print_r(array_chunk($input_array, 37","Joe"=
2));
>"43");
print_r(array_chunk($input_array, 2,
true));
print_r(array_change_key_case($age,
?> CASE_LO

Output WER));

Array ( [0] => Array – ( [0] => a– ?>


[1] => b )
Output
[1] => Array ( – [0] => c – [1] => d
Array ( [peter] => 35 [ben] => 37
)– [2] => e ) )
[joe] => 43
23
Array_Combine • array_count_values(array)

• The array_combine() function • array Required. Specifying the array


creates an array to count

by using the elements from one "keys" values of


array
array_diff_assoc
and one "values" array.
• Computes the difference of arrays
• Note: Both arrays must have equal with
number of
additional index check
elements!
Syntax
Syntax
• array array_diff_assoc ( array
array_combine(keys,values); $array1 , array

keys Required. Array of keys $array2 [, array $... ] )

values Required. Array of values Example

• <?php Returns an array

$fname=array("Peter","Ben","Joe"); containing all the values from

$age=array("35","37","43"); array1 that are not present in any of


the other
$c=array_combine($fname,$age);
arrays.
print_r($c);
• <?php
?>
$array1 = array("a" => "green", "b"
Output
=> "brown", "
Array ( [Peter] => 35 [Ben] => 37
c" => "blue", "red");
[Joe] => 43 )
$array2 = array("a" => "green",
array_count_values()
"yellow", "red");
• The array_count_values() function
$result = array_diff_assoc($array1,
counts all
$array2);
the values of an array.
print_r($result);
Syntax

24
?> • <?php

• Array ( $array1 = array('blue' => 1, 'red' =>


2, 'green' => 3, 'pu
• [b] => brown
rple' => 4);
• [c] => blue
$array2 = array('green' => 5, 'blue'
• [0] => red )
=> 6, 'yellow' => 7, 'c
array_diff_key
yan' => 8);
• —Computes the difference of arrays
var_dump(array_diff_key($array1,
using keys for
$array2));
comparison
?>
Description
output:
• arr
array(2) {
ay array_diff_key ( array $array1 ,
["red"]=> int(2)
array $array2 [,
["purple"]=> int(4)
array $... ] )
}
• Compares the keys from array1
against the keys from array_diff

array2 and returns the difference. This • Computes the difference of arrays
function is like
Description
array_diff
• array array_diff ( array $array1 ,
instead of the values. array $array2 [,

Return values array $... ] )

Returns an array difference.

() except the comparison is done on the Return value


keys
Returns an array
containing all the entries from array1
• Compares array1 against array2 and
whose keys are not present in any of returns the
the other arrays.
containing all the entries from

25
array1 that are not present in any of • <?php
the other
$array1 = array("a" => "green",
arrays. "red", "blue");

• <?php $array2 = array("b" => "green",


"yellow", "red"
$array1 = array("a" => "green",
"red", "blue", "red );

"); $result = array_intersect($array1,


$array2);
$array2 = array("b" => "green",
"yellow", "red"); print_r($result);

$result = array_diff($array1, ?>


$array2);
• The above example will output:
print_r($result);
• Array ( [a] => green [0] => red )
?>
array_merge
Output:
• —Merge one or more arrays
• Array ( [1] => blue )
Description
array_intersect
• array array_merge ( array $array1 [,
• —Computes the intersection of array $... ] )
arrays
• Merges the elements of one or more
Description arrays together so

• array array_intersect ( array that the values of one are appended to


$array1 , array the end of the

$array2 [, array $ ... ] ) previous one. It returns the resulting


array.
• array_intersect() returns an array
containing • If the input arrays have the same
string keys, then the later
all the values of array1 that are present
in all value for that key will overwrite the
previous one. If,
the arguments. Note that keys are
preserved. however, the arrays contain numeric
keys, the later value
26
will not overwrite the original value, • —Pop the element off the end of
but will be appended. array

• Values in the input array with • Description


numeric keys will be
• mixed
renumbered with incrementing keys
array_pop ( array &$array )
starting from zero in
• array_pop() pops and returns the last
the result array.
value of
• <?php
the array, shortening the array by one
$array1 = array("color" => "red", 2,
element. If array is empty (or is not an
4);
array),
$array2 = array("a", "b", "color" =>
NULL will be returned. Will
"green", "shape" => "trapezoid", 4);
additionally
$result = array_merge($array1,
produce a Warning
$array2);
array.
print_r($result);
when called on a non
?>
• <?php
output
$stack = array("orange", "banana",
:
"apple", "raspberry
Array (
");
[color] => green
$fruit = array_pop($stack);
[0] => 2
print_r($stack);
[1] => 4
?>
[2] => a
After this, $stack will have only 3
[3] => b elements:

[shape] => trapezoid Array (

[4] => 4 ) [0] => orange

array_pop [1] => banana

27
[2] => apple ) Array (

array_push [0] => orange

• —Push one or more elements onto [1] => banana


the end of array
[2] => apple
Description
[3] => raspberry )
• int array_push ( array &$array ,
array_replace
mixed
• —Replaces elements from passed
])
arrays into the first array
$var [, mixed
Description
$...
• array array_replace ( array &$array
• array_push() treats array as a stack, , array &$array1 [, array &$... ] )
and pushes the
• array_replace() replaces the values
passed variables onto the end of array. of the first array with the same
The length of
values from all the following arrays. If
array increases by the number of a key from the first array
variables pushed. Has
exists in the second array, its value will
the same effect as: be replaced by the value

• <?php from the second array. If the key exists


in the second array, and not
$array[] = $var;
the first, it will be created in the first
?>
array. If a key only exists in the
• <?php
first array, it will be left as is. If several
$stack = array("orange", "banana"); arrays are passed for

array_push($stack, "apple", replacement, they will be processed in


"raspberry"); order, the later arrays

print_r($stack); overwriting the previous values.

?> • array_replace() is not recursive : it


will replace values in the first
• The above example will output:

28
array by whatever type is in the second $preserve_keys = false ] )
array.
• Takes an input array and returns a
• <?php new array

$base = array("orange", "banana", with the order of the elements reversed.


"apple", "raspberry");
• <?php
$replacements = array(0 =>
$input = array("php", 4.0,
"pineapple", 4 => "cherry");
array("green", "red"));
$replacements2 = array(0 =>
$result = array_reverse($input);
"grape");
$result_keyed = array_reverse($input,
$basket = array_replace($base,
true);
$replacements, $replacements2);
?>
print_r($basket);
Output
?>
Array (
• The above example will output:
[0] => Array (
Array (
[0] => green
[0] => grape
[1] => red )
[1] => banana
[1] => 4
[2] => apple
[2] => php )
[3] => raspberry
Array (
[4] => cherry )
[2] => Array (
array_reverse
[0] => green
• —Return an array with elements in
reverse [1] => red )
order [1] => 4
Description [0] => php )
• array array_reverse ( array $array [, array_search
bool

29
• —Searches the array for a given • array_shift() shifts the first value of
value and the array

returns the corresponding key if off and returns it, shortening the array
successful by one

Description element and moving everything down.

• mixed • All numerical array keys will be


modified to
array_search ( mixed
start counting from zero while literal
$needle , array
keys
$haystack [, bool $strict = false ] )
won't be touched.
• <?php
• <?php
$array = array(0 => 'blue', 1 =>
$stack = array("orange", "banana",
'red', 2 => 'gree
"apple", "raspberry
n', 3 => 'red');
");
$key = array_search('green', $array);
$fruit = array_shift($stack);
// $key =
print_r($stack);
2;
?>
$key = array_search('red', $array); //
$key = 1 • The above example will output:

; Array (

?> [0] => banana

array_shift [1] => apple

• —Shift an element off the beginning [2] => raspberry )


of array
array_slice
Description
• —Extract a slice of the array
• mixed
Description
array_shift ( array &$array )
• array array_slice ( array $array , int
$offset [,

30
int $length = NULL [, bool array_splice
$preserve_keys =
• —Remove a portion of the array and
false ]] ) replace

• array_slice() returns the sequence of it with something else

elements from the array array as Description


specified by
• array array_splice ( array &$input ,
the offset and length parameters. int $offset

• <?php [, int $length = 0 [, mixed

$input = array("a", "b", "c", "d", "e"); $replacement ]] )

$output = array_slice($input, 2); • Removes the elements designated by


offset
// returns "c", "d", and "e"
and length from the input array, and
$output = array_slice($input,-2, 1); //
replaces
returns "d"
them with the elements of the
$output = array_slice($input, 0, 3); //
replacement
returns "a", "b", and "c"
array, if supplied.
// note the differences in the array keys
• <?php
print_r(array_slice($input, 2,-1));
$input = array("red", "green", "blue",
print_r(array_slice($input, 2,-1,
"yellow");
true));
$a=array_splice($input, 2);
?>
// $input is now array("red", "green")
Output:
$input = array("red", "green", "blue",
Array (
"yellow");
[0] => c
array_splice($input, 1,-1);
[1] => d )
// $input is now array("red", "yellow")
Array (
$input = array("red", "green", "blue",
[2] => c "yellow");

[3] => d )

31
array_splice($input, 1, count($input), print_r($queue);
"orange");
?>
// $input is now array("red", "orange")
• The above example will output:
array_unshift
• Array ( [0] => apple [1] =>
• —Prependone or more elements to raspberry [2] =>
the
orange [3] => banana )
beginning of an array
array_values
Description
• —Return all the values of an array
• int array_unshift ( array &$array ,
Description
mixed
• array array_values ( array $input )
mixed
• array_values() returns all the values
$... ] )
from the
$var [,
input array and indexes numerically
• array_unshift() prepends passed the array.
elements to the
• <?php
front of the array. Note that the list of
$array = array("size" => "XL",
elements
"color" => "gold"
is prepended as a whole, so that the
);
prepended
print_r(array_values($array));
elements stay in the same order. All
numerical ?>
array keys will be modified to start • The above example will output:
counting from
• Array ( [0] => XL [1] => gold )
zero while literal keys won't be
touched. arsort

• <?php • —Sort an array in reverse order and


maintain
$queue = array("orange", "banana");
index association
array_unshift($queue, "apple",
"raspberry"); Description

32
• bool arsort ( array &$array [, int • This function sorts an array such that
$sort_flags = array

SORT_REGULAR ] ) indices maintain their correlation with


the array
• This function sorts an array such that
array elements they are associated with. This
is used
indices maintain their correlation with
the mainly when sorting associative arrays
where the
array elements they are associated
with. actual element order is significant.

• <?php • <?php

$fruits = array("d" => "lemon", "a" $fruits = array("d" => "lemon", "a"
=> "orange", " => "orange", "

b" => "banana", "c" => "apple"); b" => "banana", "c" => "apple");

arsort($fruits); asort($fruits);

foreach ($fruits as $key => $val) { foreach ($fruits as $key => $val) {

echo "$key = $val\n"; echo "$key = $val\n";

} }

?> ?>

• The above example will output: • The above example will output:

• a = orange d = lemon b = banana c • c = apple b = banana d = lemon a =


= apple orange

asort count

• —Sort an array and maintain index • —Count all elements in an array, or


association
something in an object
Description
Description
• bool asort ( array &$array [, int
• int count ( mixed
$sort_flags =
$var [, int $mode =
SORT_REGULAR ] )

33
COUNT_NORMAL ] ) $varname [, mixed

• Counts all elements in an array, or $... ] )


something
, this is not really a function, but a
in an object.
language construct. list() is used to
• <?php assign a

$a[0] = 1; list of variables in one operation.

$a[1] = 3; • <?php

$a[2] = 5; $info = array('coffee', 'brown',


'caffeine');
$result = count($a);
// Listing all the variables
// $result == 3
list($drink, $color, $power) = $info;
$b[0] = 7;
echo "$drink is $color and $power
$b[5] = 9;
makes it special.\n";
$b[10] = 11;
// Listing some of them
$result = count($b);
list($drink, , $power) = $info;
// $result == 3
echo "$drink has $power.\n";
$result = count(null);
// Or let's skip to only the third one
// $result == 0
list( , , $power) = $info;
$result = count(false);
echo "I need $power!\n";
// $result == 1
// list() doesn't work with strings
?>
list($bar) = "abcde";
list
var_dump($bar); // NULL
• —Assign variables as if they were an
sort
array
• —Sort an array
Description
Description
• array list ( mixed

• Like array()

34
• bool sort ( array &$array [, int number
$sort_flags =
$start , mixed
SORT_REGULAR ] )
$step = 1 ] )
• This function sorts an array.
$limit [,
Elements will be
• Create an array containing a range of
arranged from lowest to highest when
this elements.
function has completed. • <?php
• <?php // array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12)
$fruits = array("lemon", "orange",
"banana", "apple"); foreach (range(0, 12) as $number) {
sort($fruits); }
foreach ($fruits as $key => $val) { echo $number;
} // The step parameter was introduced
in 5.0.0
echo "fruits[" . $key . "] = " . $val .
"\n"; // array(0, 10, 20, 30, 40, 50, 60, 70,
80, 90, 100)
?>
foreach (range(0, 100, 10) as
• The above example will output:
$number) {
• fruits[0] = apple fruits[1] = banana
}
fruits[2] = lemon
echo $number;
fruits[3] = orange
// Use of character sequences
range
introduced in 4.1.0
• —Create an array containing a
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
range of
'i');
elements
foreach (range('a', 'i') as $letter) {
• Description
}
• array range ( mixed
echo $letter;

35
// array('c', 'b', 'a'); • Note: If the search parameter is a
string and the type parameter is
foreach (range('c', 'a') as $letter) {
set to TRUE, the search is case-
}
sensitive.
echo $letter;
• Syntax
?>
• in_array(search,array,type)
shuffle

• —Shuffle an array
Parameter Description
• Description
• search-Specifies the what to search
• bool shuffle ( array &$array ) for

• This function shuffles (randomizes • array. Specifies the array to search


the order
• typeOptional. If this parameter is set
of the elements in) an array. to TRUE, the in_array()

• <?php function searches for the search-string


and specific type in the
$numbers = range(1, 20);
array.
shuffle($numbers);
• <?php
foreach ($numbers as $number) {
$people = array("Peter", "Joe",
echo "$number "; "Glenn", "Cleveland");
} if (in_array("Glenn", $people))
?> {
• sizeof — Alias of count() echo "Match found";
Description }
• This function is an alias of: count() else
. {
• The in_array() function searches an echo "Match not found";
array for a specific value.
}

36
?>

html

Copy code

2.2 PHP Functions <html>

What is a Function? <body>

A function is a block of code designed <?php


to accomplish a specific task. A
// Defining function: printHello
function is executed when it is called. It
may return a value or may not return function printHello()
any value.
{

echo "Hello";
A Function That Does Not Return a
Value }

To define a function that does not // Calling the function: printHello


return a value, you can use the printHello();
following syntax:
?>

</body>
php
</html>
Copy code
A Function That Returns a Value
function function_name()
When you want to get the value
{ generated from a function to be used
// statements elsewhere in your code, you need to
define a function that can return a
} value. The return keyword is used to
return the value of the function to
Note: The name of the function must
another function or code block that
start with a letter or an underscore; it
calls it.
cannot start with a number.

Syntax:
Example:

37
</body>

php </html>

Copy code Function Parameters

function function_name() Parameters are values passed to the


function. You can pass more than one
{
parameter to the function by separating
// statements them with commas.

return value;

} Example:

Example:
html

html Copy code

Copy code <html>

<html> <body>

<body> <?php

<?php // Defining function: printName

// Defining function: sum function printName($name)

function sum() {

{ echo "Hello " . $name;

$s = 10 + 20; }

return $s; // Calling the function: printName

} printName("Khorn Channa");

// Calling the function: sum ?>

$total = sum(); </body>

echo "Total = " . $total; </html>

?> 2.3 PHP - GET & POST Methods

38
There are two ways the browser client http://www.test.com/index.htm?name1
can send information to the web server: =value1&name2=value2

The POST Method The GET method produces a long


string that appears in your server logs
Before the browser sends the
and in the browser's Location box.
information, it encodes it using a
scheme called URL encoding. In this The GET method is restricted to send
scheme, name/value pairs are joined up to 1024 characters only.
with equal signs, and different pairs
Never use the GET method if you have
are separated by the ampersand:
passwords or other sensitive
information to send to the server.

makefile GET can't be used to send binary data,


like images or Word documents, to the
Copy code
server.
name1=value1&name2=value2&name
The data sent by the GET method can
3=value3
be accessed using the
Spaces are removed and replaced with QUERY_STRING environment
the + character, and any other non- variable.
alphanumeric characters are replaced
PHP provides the $_GET associative
with hexadecimal values. After the
array to access all the sent information
information is encoded, it is sent to the
using the GET method.
server.
Example of GET Method

Try out the following example by


The GET Method
putting the source code in test.php
The GET method sends the encoded script.
user information appended to the page
request. The page and the encoded
information are separated by the ? php
character.
Copy code

<?php
arduino
if ($_GET["name"] || $_GET["age"]) {
Copy code
echo "Welcome " . $_GET['name'] .
"<br />";

39
echo "You are " . $_GET['age'] . " The POST method can be used to send
years old."; ASCII as well as binary data.

exit(); The data sent by the POST method goes


through HTTP headers, so security
}
depends on the HTTP protocol. By
?> using Secure HTTP, you can ensure
that your information is secure.
<html>
PHP provides the $_POST associative
<body> array to access all the sent information
<form action="<?php $_PHP_SELF using the POST method.
?>" method="GET"> Example of POST Method
Name: <input type="text" Try out the following example by
name="name" /> putting the source code in test.php
Age: <input type="text" script.
name="age" />

<input type="submit" /> php


</form> Copy code
</body> <?php
</html> if ($_POST["name"] ||
It will produce the following result: $_POST["age"]) {

if (preg_match("/[^A-Za-z'-]/",
$_POST['name'])) {
The POST Method
die("Invalid name; name should
The POST method transfers be alphabetical.");
information via HTTP headers. The
information is encoded as described in }
the case of the GET method and put echo "Welcome " . $_POST['name'] .
into a header called QUERY_STRING. "<br />";

echo "You are " . $_POST['age'] . "


The POST method does not have any years old.";
restriction on the data size to be sent. exit();

40
} php

?> <?php

<html> if ($_REQUEST["name"] ||
$_REQUEST["age"]) {
<body>
echo "Welcome " .
<form action="<?php $_PHP_SELF
$_REQUEST['name'] . "<br />";
?>" method="POST">
echo "You are " .
Name: <input type="text"
$_REQUEST['age'] . " years old.";
name="name" />
exit();
Age: <input type="text"
name="age" /> }

<input type="submit" /> ?>

</form> <html>

</body> <body>

</html> <form action="<?php $_PHP_SELF


?>" method="POST">
It will produce the following result:
Name: <input type="text"
The $_REQUEST Variable
name="name" />
The PHP $_REQUEST variable
Age: <input type="text"
contains the contents of both $_GET,
name="age" />
$_POST, and $_COOKIE. We will
discuss the $_COOKIE variable when <input type="submit" />
we explain cookies. The PHP
</form>
$_REQUEST variable can be used to
get the result from form data sent with </body>
both the GET and POST methods.
</html>

Here, the $_PHP_SELF variable


Example of $_REQUEST Variable contains the name of the script in which
it is being called.
Try out the following example by
putting the source code in test.php
script.
It will produce the following result:

41
PHP Form Introduction $gender =
test_input($_POST["gender"]);
Example
}
Below is an example that shows the
form with some specific actions using
the POST method.
function test_input($data) {
Html
$data = trim($data);

$data = stripslashes($data);
<html>
$data =
<head> htmlspecialchars($data);

<title>PHP Form Validation</title> return $data;

</head> }

<body> ?>

<?php

// Define variables and set to <h2>Classes Registration</h2>


empty values

$name = $email = $gender =


<form method="post"
$comment = $website = "";
action="/view.php">

<table>
if
<tr>
($_SERVER["REQUEST_METHOD"]
== "POST") { <td>Name:</td>
$name = <td><input type="text"
test_input($_POST["name"]); name="name"></td>
$email = </tr>
test_input($_POST["email"]);
<tr>
$website =
test_input($_POST["website"]); <td>E-mail:</td>

$comment = <td><input type="text"


test_input($_POST["comment"]); name="email"></td>

42
</tr> </tr>

<tr> </table>

<td>Specific Time:</td> </form>

<td><input type="text"
name="website"></td>
<?php
</tr>
echo "<h2>Your Given Details
<tr> Are:</h2>";

<td>Class details:</td> echo $name;

<td><textarea echo "<br>";


name="comment" rows="5"
echo $email;
cols="40"></textarea></td>
echo "<br>";
</tr>
echo $website;
<tr>
echo "<br>";
<td>Gender:</td>
echo $comment;
<td>
echo "<br>";
<input type="radio"
name="gender" echo $gender;
value="female">Female
?>
<input type="radio"
name="gender" value="male">Male </body>

</td> </html>

</tr>

<tr>

<td>

<input type="submit" PHP String Built-in Functions


name="submit" value="Submit"> Introduction to String Functions
</td> String functions are essential in PHP
for manipulating and processing text.

43
PHP provides a wide range of built-in echo $newText; // Outputs: 'I love
string functions. coding'

Some commonly used string functions 3. strpos(): Find Position of Substring


include:
Description: Finds the position of the
strlen() first occurrence of a substring in a
string.
str_replace()
Example:
strpos()
php
substr()
Copy code
strtoupper() and strtolower()
$text = 'Hello World';
Commonly Used String Functions
$pos = strpos($text, 'World');
1. strlen(): Get the Length of a String
echo $pos; // Outputs: 6 (position of
Description: Returns the length of a
'World' starts at index 6)
string (number of characters).
4. substr(): Extract a Part of a String
Example:
Description: Returns a part of a string
php
starting at a specified position.
Copy code
Example:
$str = 'Hello World';
php
echo strlen($str); // Outputs: 11
Copy code
2. str_replace(): Replace Substring
$text = 'Hello World';
Description: Replaces all occurrences
$part = substr($text, 6, 5);
of a substring with another substring.
echo $part; // Outputs: 'World' (5
Example:
characters starting from position 6)
php
5. strtoupper(): Change Case to
Copy code Uppercase

$text = 'I love PHP'; Description: Converts a string to


uppercase.
$newText = str_replace('PHP',
'coding', $text); Example:

44
php Description: Converts the first
character of a string to lowercase.
Copy code
Example:
$text = 'Hello World';
php
echo strtoupper($text); // Outputs:
'HELLO WORLD' Copy code

6. strtolower(): Change Case to $text = 'Hello World';


Lowercase
echo lcfirst($text); // Outputs: 'hello
Description: Converts a string to World'
lowercase.
9. ucwords(): Capitalize the First
Example: Character of Each Word

php Description: Capitalizes the first


character of each word.
Copy code
Example:
$text = 'HELLO WORLD';
php
echo strtolower($text); // Outputs:
'hello world' Copy code

7. ucfirst(): Capitalize the First $text = 'hello world';


Character
echo ucwords($text); // Outputs: 'Hello
Description: Capitalizes the first World'
character of a string.
10. strrev(): Reverse a String
Example:
Description: Reverses a string.
php
Example:
Copy code
php
$text = 'hello world';
Copy code
echo ucfirst($text); // Outputs: 'Hello
$text = 'hello';
world'
echo strrev($text); // Outputs: 'olleh'
8. lcfirst(): Lowercase the First
Character 11. explode(): Split a String into an
Array

45
Description: Splits a string into an $text = ' Hello World ';
array by a delimiter.
echo trim($text); // Outputs: 'Hello
Example: World'

php 14. ltrim(): Remove Whitespace from


the Beginning
Copy code
Description: Removes whitespace from
$text = 'apple,banana,cherry';
the beginning of a string.
$fruits = explode(',', $text);
Example:
print_r($fruits); // Outputs: Array([0]
php
=> apple, [1] => banana, [2] =>
cherry) Copy code

12. implode(): Join Array Elements $text = ' Hello World';


into a String
echo ltrim($text); // Outputs: 'Hello
Description: Joins array elements into World'
a string.
15. rtrim(): Remove Whitespace from
Example: the End

php Description: Removes whitespace from


the end of a string.
Copy code
Example:
$fruits = ['apple', 'banana', 'cherry'];
php
$text = implode(',', $fruits);
Copy code
echo $text; // Outputs:
'apple,banana,cherry' $text = 'Hello World ';

13. trim(): Remove Whitespace from echo rtrim($text); // Outputs: 'Hello


the Start and End World'

Description: Removes whitespace from 16. str_split(): Split a String into an


the start and end of a string. Array by a Specific Length

Example: Description: Splits a string into an


array by a specific length.
php
Example:
Copy code

46
php Definition

Copy code Server-side programming involves


writing programs in various web
$text = 'hello';
programming languages/frameworks
$chars = str_split($text, 2); to:

print_r($chars); // Outputs: Array([0] Dynamically edit, change, or add


=> 'he', [1] => 'll', [2] => 'o') content to a web page.

3. PHP Server-Side Basics Respond to user queries or data


submitted from HTML forms.

Access data or databases and return


URLs and Web Servers the results to a browser.
3.1 Overview of URL Structure Customize web pages for individual
A typical URL format: users.
http://server/path/file Provide security since server code
Process when a URL is entered in a cannot be viewed from a browser.
browser: Examples of Server-Side Languages
The computer looks up the server's IP PHP, Java/JSP, Ruby on Rails,
address using DNS. ASP.NET, Python, Perl, etc.
The browser connects to that IP Web Server Functionality
address and requests the specified file.
The web server contains software that
The web server software (e.g., Apache) allows it to run server-side programs
retrieves the file from the server's local and sends back their output as
file system. responses to web requests. Each
The server sends the file's contents language/framework has its pros and
back to the browser. cons, and in this context, we use PHP.

Example of URL Request What is PHP?

For instance, the URL PHP stands for "PHP Hypertext


http://www.facebook.com/home.php Preprocessor."
tells the server to run the program A server-side scripting language used
home.php and return its output. to create dynamic web pages:
Server-Side Web Programming

47
Provides different content depending Syntax: $variable_name = value;
on the context.
Example:
Interfaces with services such as
php
databases and email.
Copy code
Authenticates users and processes form
information. $user_name = "ram80";
PHP code can be embedded within $age = 16;
HTML code.
$drinking_age = $age + 5;
Lifecycle of a PHP Web Request
$this_class_rocks = TRUE;
User's computer requests a .php file.
Variable names are case-sensitive,
The server processes the request and always begin with $, and are implicitly
returns the output. declared by assignment.
Basic PHP Syntax Data Types
PHP Syntax Template Basic types include: int, float, boolean,
string, array, object, NULL.
Code between <?php and ?> is
executed as PHP. PHP automatically converts between
types in many cases.
Everything outside these tags is output
as pure HTML.

Example of PHP Syntax Type Casting


php Use (type) to cast variables:
Copy code php
<?php Copy code
print "Hello, world!"; $age = (int) "21";
?> PHP Operators
Output: Hello, world! Arithmetic Operators
PHP Variables Operators: +, -, *, /, %, ., ++
Variable Declaration Assignment Operators: =, +=, -=, *=,
/=, %=, .=

48
Comments Object Data Type

Single-line comments: # or // php

Multi-line comments: /* comment */ class Car {

PHP Data Types Overview public $color;

String Data Type public function __construct($color) {

php $this->color = $color;

$string_var = "Hello, World!"; }

echo $string_var; // Outputs: Hello, public function get_color() {


World!
return $this->color;
Integer Data Type
}
php
}
$int_var = 42;
$my_car = new Car("red");
echo $int_var; // Outputs: 42
echo $my_car->get_color(); //
Float Data Type Outputs: red

php NULL Data Type

$float_var = 3.14; php

echo $float_var; // Outputs: 3.14 $null_var = NULL;

Boolean Data Type echo $null_var; // Outputs nothing

php Resource Data Type

$bool_var = true; php

echo $bool_var; // Outputs: 1 (true) $file = fopen("example.txt", "r");

Array Data Type echo fread($file,


filesize("example.txt"));
php
fclose($file);
$array_var = array("apple", "banana",
"cherry"); php

echo $array_var[0]; // Outputs: apple $name = "Stefanie Hatcher";

49
$length = strlen($name); // 15 // statements;

$index = strpos($name, "e"); // 2 }

$first = substr($name, 9, 5); // "Hatch" For Loop

$name = strtoupper($name); // php


"STEFANIE HATCHER"
Copy code
3.2 Interpreted Strings
for ($i = 0; $i < 10; $i++) {
Variable Interpolation in Strings
print "$i squared is " . $i * $i . ".\n";
Strings within double quotes (")
}
interpret variables:
While Loop
php
php
$age = 16;
Copy code
print "You are $age years old."; // You
are 16 years old. while (condition) {
Strings within single quotes (') do not // statements;
interpret variables:
}
php
Do-While Loop
Copy code
php
print 'You are $age years old.'; // You
are $age years old. Copy code

Control Structures do {

If/Else Statement // statements;

php } while (condition);

if (condition) { Math Operations and Functions

// statements; Common functions include: abs(),


ceil(), floor(), log(), sqrt(), etc.
} elseif (condition) {
Example:
// statements;
php
} else {

50
Copy code $name[] = value; # Append value

$a = 3; Example:

$b = 4; php

$c = sqrt(pow($a, 2) + pow($b, 2)); // Copy code


c=5
$a = array(); # Empty array (length 0)
Int and Float Types
$a[0] = 23; # Stores 23 at index 0
Example of type conversion: (length 1)

php $a2 = array("some", "strings", "in",


"an", "array");
Copy code
$a2[] = "Ooh!"; # Add string to end
$a = 7 / 2; // float: 3.5
(at index 5)
$b = (int) $a; // int: 3
Array Functions
$c = round($a); // float: 4.0
Function Description

count Number of elements in the array

print_r Print array's contents


PHP Arrays - Functions
array_pop, array_push, array_shift,
array_unshift Using array as a
stack/queue
3.3 Basic PHP Syntax
in_array, array_search, array_reverse,
Arrays sort, rsort, shuffle Searching and
Creating Arrays: reordering

$name = array(); # Create an empty array_fill, array_merge,


array array_intersect, array_diff,
array_slice, range Creating, filling,
$name = array(value0, value1, ..., filtering
valueN); # Create an array with values
array_sum, array_product,
$name[index] # Get element value array_unique, array_filter,
$name[index] = value; # Set element array_reduce Processing elements
value Array Function Example

51
Arrays in PHP replace many other php
collections in Java (list, stack, queue,
Copy code
set, map).
$fellowship = array("Frodo", "Sam",
php
"Gandalf", "Strider", "Gimli",
Copy code "Legolas", "Boromir");

$tas = array("MD", "BH", "KK", print "The fellowship of the ring


"HM", "JP"); members are: \n";

for ($i = 0; $i < count($tas); $i++) {

$tas[$i] = strtolower($tas[$i]); foreach ($fellowship as $fellow) {

} print "$fellow\n";

$morgan = array_shift($tas); }

array_pop($tas); Multidimensional Arrays

array_push($tas, "ms"); Example:

array_reverse($tas); php

sort($tas); Copy code

$best = array_slice($tas, 1, 2); $AmazonProducts = array(

Foreach Loop array("Code" => "BOOK",


"Description" => "Books", "Price" =>
Syntax:
50),

array("Code" => "DVDs",


php "Description" => "Movies", "Price"
=> 15),
Copy code
array("Code" => "CDs",
foreach ($array as $variableName) { "Description" => "Music", "Price" =>
... 20)

} );

Example:
for ($row = 0; $row < 3; $row++) {

52
echo "<p> | " . print strpos($test, "o", 5); // Output:
$AmazonProducts[$row]["Code"] . " | position of "o" after index 5
".
Regular Expressions

Patterns in Text:
$AmazonProducts[$row]["Description
"] . " | " . PHP supports POSIX and Perl regular
expressions.
$AmazonProducts[$row]["Price"]
. " </p>"; Examples:
} regex
String Comparison Functions Copy code
Common Functions: [a-z]at # Matches: cat, rat, bat…
strcmp: Compare strings [aeiou] # Matches vowels
strstr, strchr: Find string/char within a [a-zA-Z] # Matches all letters
string
[^a-z] # Not a-z
strpos: Find numerical position of
string [[:alnum:]]+ # At least one
alphanumeric character
str_replace, substr_replace: Replace
strings (very)*large # Matches: large, very
large, very very large…
Example:
(very){1,3} # Counting "very" up to 3
php
^bob # Matches "bob" at the
Copy code beginning
$offensive = array("offensive word1", com$ # Matches "com" at the end
"offensive word2");
Printing HTML Tags in PHP
$feedback = str_replace($offensive,
"%!@*", $feedback); Best practice is to minimize print/echo
statements.

Without print, how to insert dynamic


$test = "Hello World! \n"; content?
print strpos($test, "o"); // Output: Example:
position of first "o"

53
php Unclosed Braces: Results in an error
about 'unexpected $end'.
Copy code
Missing '=' Sign: In <?=, the
print "<!DOCTYPE html PUBLIC \"-
expression does not produce any
//W3C//DTD XHTML 1.1//EN\"\n";
output.
print "
Example:
\"http://www.w3.org/TR/xhtml11/DTD/
xhtml11.dtd\">\n"; php

print "<html Copy code


xmlns=\"http://www.w3.org/1999/xhtml
<body>
\">\n";
<p>Watch how high I can count:
print "<head>\n";
<?php
print "<title>Geneva's web
page</title>\n"; for ($i = 1; $i <= 10; $i++) {
... ?>
for ($i = 1; $i <= 10; $i++) { <?= $i ?>
print "<p> I can count to $i! </p>
</p>\n";
</body>
}
Complex Expression Blocks
PHP Expression Blocks
Example:
Short syntax for embedding PHP
expressions into HTML. php

Syntax: <?= expression ?> Copy code

Example: <body>

php <?php

Copy code for ($i = 1; $i <= 3; $i++) {

<h2> The answer is <?= 6 * 7 ?> ?>


</h2> <h<?= $i ?>>This is a level <?= $i
Common Errors ?> heading.</h<?= $i ?>>

54
<?php for ($i = 1; $i < strlen($str);
$i++) {
}
print $separator . $str[$i];
?>
}
</body>
}
Functions
}
Parameter types and return types are
not explicitly defined.

A function with no return statements print_separated("hello"); # Output:


implicitly returns NULL. h, e, l, l, o

Example: print_separated("hello", "-"); #


Output: h-e-l-l-o
php

Copy code

function quadratic($a, $b, $c) {

return -$b + sqrt($b * $b - 4 * $a *


$c) / (2 * $a);

Default Parameter Values

If no value is passed, the default will be


used.

Example:

php

Copy code

function print_separated($str,
$separator = ", ") {

if (strlen($str) > 0) {

print $str[0];

55

You might also like