Simple PHP Training PDF
Simple PHP Training PDF
PHP BASIC
1
Web service ............................................................................................................................................... 8
Web service architecture & Introduction.............................................................................................. 8
Comparison between Web services .................................................................................................. 24
PHP Introduction .................................................................................................................................... 27
What is needed? ...................................................................................................................27
What is PHP ..........................................................................................................................28
What You Should Already Know ............................................................................................28
What is PHP? ........................................................................................................................28
What is a PHP File? ..............................................................................................................28
What Can PHP Do?...............................................................................................................28
Why PHP? .............................................................................................................................29
How does PHP work?............................................................................................................29
PHP Installation.......................................................................................................................30
What Do I Need for PHP Installation? ....................................................................................30
Use a Web Host with PHP Support .......................................................................................31
Install PHP on your computer ................................................................................................31
Option 3: XAMPP ..................................................................................................................31
Download XAMPP .................................................................................................................31
Install XAMPP .......................................................................................................................31
Test .......................................................................................................................................33
Common Xampp problems ....................................................................................................34
PHP Syntax ..............................................................................................................................35
Basic PHP Syntax .................................................................................................................35
Example ................................................................................................................................36
Comments in PHP ...................................................................................................................36
PHP Variables and Constants ................................................................................................37
What is Variables in PHP.......................................................................................................37
Naming Conventions for PHP Variables ................................................................................38
PHP Data Types ...................................................................................................................................... 41
Data Types in PHP ................................................................................................................41
Booleans ...............................................................................................................................42
Integers .................................................................................................................................43
Floating point numbers ..........................................................................................................45
Strings ...................................................................................................................................45
2
NULL: ....................................................................................................................................49
Arrays ....................................................................................................................................49
PHP Operators ........................................................................................................................51
PHP Arithmetic Operators .....................................................................................................52
PHP Assignment Operators...................................................................................................52
PHP Incrementing/Decrementing Operators ..........................................................................53
PHP Comparison Operators ..................................................................................................54
PHP Logical Operators ..........................................................................................................55
PHP Array Operators.............................................................................................................56
PHP String Operators ............................................................................................................56
PHP Control Structures ..........................................................................................................57
PHP Conditional Statements .................................................................................................57
The if Statement ....................................................................................................................58
The If…Else Statement .........................................................................................................58
The ElseIf Statement .............................................................................................................60
The Switch Statement ...........................................................................................................61
Alternative syntax for control structures .................................................................................64
PHP Loops ............................................................................................................................66
The while Loop ......................................................................................................................66
The do…while Statement ......................................................................................................67
The for Loop ..........................................................................................................................67
The foreach Loop ..................................................................................................................69
continue.................................................................................................................................70
PHP Include Files ..................................................................................................................71
The include() Function ...........................................................................................................71
The require() Function ...........................................................................................................73
goto .......................................................................................................................................74
PHP Functions ........................................................................................................................................ 75
Table of Contents ..................................................................................................................75
Internal (Built-in) Functions ....................................................................................................75
User-defined functions...........................................................................................................75
Create a PHP Function ..........................................................................................................76
Functions with Parameters ....................................................................................................78
Functions with Optional Parameters and Default Values .......................................................78
Function arguments ...............................................................................................................79
3
Returning values ...................................................................................................................81
Variable functions ..................................................................................................................82
Anonymous functions ............................................................................................................83
PHP Strings ............................................................................................................................................. 84
What is String in PHP ............................................................................................................84
Manipulating PHP Strings ......................................................................................................84
Calculating the Length of a String ..........................................................................................84
Counting Number of Words in a String ..................................................................................84
Replacing Text within Strings ................................................................................................85
Reversing a String .................................................................................................................85
String Functions ....................................................................................................................86
PHP Arrays ..............................................................................................................................91
Create an Array in PHP .........................................................................................................92
PHP Indexed Arrays ..............................................................................................................92
Get The Length of an Array – The count() Function ...............................................................93
Loop Through an Indexed Array ............................................................................................93
Associative Arrays .................................................................................................................93
Loop Through an Associative Array .......................................................................................94
Multidimensional Arrays ........................................................................................................95
PHP Sorting Arrays .................................................................................................................96
Sort Functions for Arrays .......................................................................................................96
Sort Array in Ascending Order – sort() ...................................................................................96
Sort Array in Descending Order – rsort() ...............................................................................97
Sort Array in Ascending Order, According to Value – asort() .................................................97
Sort Array in Ascending Order, According to Key – ksort() ....................................................98
Sort Array in Descending Order, According to Value – arsort() ..............................................98
Sort Array in Descending Order, According to Key – krsort() .................................................98
List of Array Functions with Example .....................................................................................99
array_change_key_case() .....................................................................................................99
array_chunk() ........................................................................................................................99
array_column() ......................................................................................................................99
array_combine() ....................................................................................................................99
array_count_values() ...........................................................................................................100
array_diff() ...........................................................................................................................100
array_diff_assoc() ................................................................................................................100
4
array_diff_key() ...................................................................................................................100
array_diff_uassoc() ..............................................................................................................100
array_diff_ukey() .................................................................................................................101
array_fill() ............................................................................................................................101
array_fill_keys() ...................................................................................................................101
array_filter() .........................................................................................................................101
array_flip() ...........................................................................................................................102
array_intersect() ..................................................................................................................102
array_intersect_assoc() .......................................................................................................102
array_intersect_key() ...........................................................................................................102
array_intersect_uassoc() .....................................................................................................102
array_intersect_ukey() .........................................................................................................103
array_key_exists() ...............................................................................................................103
array_keys() ........................................................................................................................103
array_map() .........................................................................................................................104
array_merge()......................................................................................................................104
The array_merge() function merges one or more arrays into one array. ..............................104
array_merge_recursive() .....................................................................................................104
array_multisort() ..................................................................................................................104
array_pad() ..........................................................................................................................104
array_pop() ..........................................................................................................................105
array_push() ........................................................................................................................105
array_rand().........................................................................................................................105
array_reduce() .....................................................................................................................105
array_replace() ....................................................................................................................105
array_replace_recursive() ....................................................................................................106
array_reverse() ....................................................................................................................106
array_search() .....................................................................................................................106
array_shift() .........................................................................................................................106
array_slice().........................................................................................................................106
array_splice().......................................................................................................................107
array_sum() .........................................................................................................................107
array_udiff() .........................................................................................................................107
array_udiff() .........................................................................................................................107
array_udiff() .........................................................................................................................108
5
array_udiff_uassoc() ............................................................................................................108
array_uintersect() ................................................................................................................108
array_uintersect_assoc() .....................................................................................................109
array_uintersect_uassoc() ...................................................................................................109
array_unique() .....................................................................................................................110
array_unshift() .....................................................................................................................110
array_values() .....................................................................................................................110
array_walk().........................................................................................................................110
array_walk_recursive() ........................................................................................................111
arsort().................................................................................................................................111
asort() ..................................................................................................................................111
compact() ............................................................................................................................111
count() .................................................................................................................................111
current()...............................................................................................................................111
in_array() .............................................................................................................................112
krsort() .................................................................................................................................112
ksort() ..................................................................................................................................112
pos() ....................................................................................................................................113
rsort()...................................................................................................................................113
sizeof() ................................................................................................................................113
sort() ....................................................................................................................................113
uasort() ................................................................................................................................113
uksort() ................................................................................................................................113
usort() ..................................................................................................................................114
shuffle() ...............................................................................................................................114
PHP GET and POST ............................................................................................................................. 114
Methods of Sending Information to Server ...........................................................................114
The GET Method .................................................................................................................114
Advantages and Disadvantages of Using the GET Method .................................................115
The POST Method...............................................................................................................115
Advantages and Disadvantages of Using the POST Method ...............................................116
The $_REQUEST Variable ..................................................................................................116
6
[Blank Page]
7
Web service
Web services is a standardized way or medium to propagate
communication between the client and server applications on the
World Wide Web.
Most often than not, these heterogeneous applications need some sort of communication to happen
between them. Since they are built using different development languages, it becomes really difficult to
ensure accurate communication between applications.
Here is where web services come in. Web services provide a common platform that allows multiple
applications built on various programming languages to have the ability to communicate with each other.
The web services can be searched for over the network and can also be invoked accordingly.
When invoked the web service would be able to provide functionality to the client which invokes
that web service.
8
The above diagram shows a very simplistic view of how a web service would actually work. The client
would invoke a series of web service calls via requests to a server which would host the actual web
service.
These requests are made through what is known as remote procedure calls. Remote Procedure
Calls(RPC) are calls made to methods which are hosted by the relevant web service.
As an example, Aamzon provides a web service that provides prices for products sold online via
amazon.com. The front end or presentation layer can be in .Net or Java but either programming language
would have the ability to communicate with the web service.
The main component of a web service is the data which is transferred between the client and the server,
and that is XML. XML (Extensible markup language) is a counterpart to HTML and easy to understand
the intermediate language that is understood by many programming languages.
So when applications talk to each other, they actually talk in XML. This provides a common platform for
application developed on various programming languages to talk to each other.
Web services use something known as SOAP (Simple Object Access Protocol) for sending the XML data
between applications. The data is sent over normal HTTP. The data which is sent from the web service to
the application is called a SOAP message. The SOAP message is nothing but an XML document. Since
the document is written in XML, the client application calling the web service can be written in any
programming language.
9
Web service Components
In order for a web service to be fully functional, there are certain components that need to be in place.
These components need to be present irrespective of whatever development language is used for
programming the web service.
SOAP is known as a transport-independent messaging protocol. SOAP is based on transferring XML data
as SOAP Messages. Each message has something which is known as an XML document. Only the
structure of the XML document follows a specific pattern, but not the content. The best part of Web
services and SOAP is that its all sent via HTTP, which is the standard web protocol.
Each SOAP document needs to have a root element known as the <Envelope> element. The root
element is the first element in an XML document.
The "envelope" is in turn divided into 2 parts. The first is the header and the next is the body.
The header contains the routing data which is basically the information which tells the XML
document to which client it needs to be sent to.
The body will contain the actual message.
The diagram below shows a simple example of the communication via SOAP.
10
WSDL (Web services description language)
A web service cannot be used if it cannot be found. The client invoking the web service should know
where the web service actually resides.
Secondly, the client application needs to know what the web service actually does, so that it can invoke
the right web service. This is done with the help of the WSDL, known as the Web services description
language. The WSDL file is again an XML-based file which basically tells the client application what the
web service does. By using the WSDL document, the client application would be able to understand
where the web service is located and how it can be utilized.
<definitions>
<message name="TutorialRequest">
</message>
<message name="TutorialResponse">
</message>
<portType name="Tutorial_PortType">
<operation name="Tutorial">
<input message="tns:TutorialRequest"/>
<output message="tns:TutorialResponse"/>
</operation>
</portType>
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="Tutorial">
<soap:operation soapAction="Tutorial"/>
11
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:Tutorialservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:Tutorialservice"
use="encoded"/>
</output>
</operation>
</binding>
</definitions>
The important aspects to note about the above WSDL declaration are as follows;
1. . <message> - The message parameter in the WSDL definition is used to define the different
data elements for each operation performed by the web service. So in the example above, we
have 2 messages which can be exchanged between the web service and the client application,
one is the "TutorialRequest", and the other is the "TutorialResponse" operation. The
TutorialRequest contains an element called "TutorialID" which is of the type string. Similarly, the
TutorialResponse operation contains an element called "TutorialName" which is also a type
string.
2. <portType> - This actually describes the operation which can be performed by the web service,
which in our case is called Tutorial. This operation can take 2 messages; one is an input
message, and the other is the output message.
3. <binding> - This element contains the protocol which is used. So in our case, we are defining it
to use http (http://schemas.xmlsoap.org/soap/http). We also specify other details for the body
of the operation, like the namespace and whether the message should be encoded.
12
Universal Description, Discovery and Integration (UDDI)
UDDI is a standard for describing, publishing, and discovering the web services that is provided by a
particular service provider. It provides a specification which helps in hosting the information on web
services.
Now we discussed in the previous topic about WSDL and how it contains information on what the Web
service actually does. But how can a client application locate a WSDL file to understand the various
operations offered by a web service. So UDDI is the answer to this and provides a repository on which
WSDL files can be hosted. So the client application will have complete access to the UDDI, which acts as
a database containing all the WSDL files.
Just as a telephone directory has the name, address and telephone number of a particular person, the
same way the UDDI registry will have the relevant information for the web service. So that a client
application knows, where it can be found.
But let's look at some other advantages of why it is important to use web services.
1. Exposing Business Functionality on the network - A web service is a unit of managed code that
provides some sort of functionality to client applications or end users. This functionality can be
invoked over the HTTP protocol which means that it can also be invoked over the internet.
Nowadays all applications are on the internet which makes the purpose of Web services more
useful. That means the web service can be anywhere on the internet and provide the necessary
functionality as required.
2. Interoperability amongst applications - Web services allow various applications to talk to each
other and share data and services among themselves. All types of applications can talk to each
other. So instead of writing specific code which can only be understood by specific applications,
you can now write generic code that can be understood by all applications
3. A Standardized Protocol which everybody understands - Web services use standardized industry
protocol for the communication. All the four layers (Service Transport, XML Messaging, Service
Description, and Service Discovery layers) uses well-defined protocols in the web services
protocol stack.
4. Reduction in cost of communication - Web services use SOAP over HTTP protocol, so you can
use your existing low-cost internet for implementing web services.
13
Web service Architecture
Every framework needs some sort of architecture to make sure the entire framework works as desired.
Similarly, in web services, there is an architecture which consists of three distinct roles as given below
1. Provider - The provider creates the web service and makes it available to client application who
want to use it.
2. Requestor - A requestor is nothing but the client application that needs to contact a web service.
The client application can be a .Net, Java, or any other language based application which looks
for some sort of functionality via a web service.
3. Broker - The broker is nothing but the application which provides access to the UDDI. The UDDI,
as discussed in the earlier topic enables the client application to locate the web service.
The diagram below showcases how the Service provider, the Service requestor and Service registry
interact with each other.
1. Publish - A provider informs the broker (service registry) about the existence of the web service
by using the broker's publish interface to make the service accessible to clients
2. Find - The requestor consults the broker to locate a published web service
14
3. Bind - With the information it gained from the broker(service registry) about the web service, the
requestor is able to bind, or invoke, the web service.
1. They are XML-Based - Web Services uses XML to represent the data at the representation and
data transportation layers. Using XML eliminates any networking, operating system, or platform
sort of dependency since XML is the common language understood by all.
2. Loosely Coupled – Loosely coupled means that the client and the web service are not bound to
each other, which means that even if the web service changes over time, it should not change the
way the client calls the web service. Adopting a loosely coupled architecture tends to make
software systems more manageable and allows simpler integration between different systems.
3. Synchronous or Asynchronous functionality- Synchronicity refers to the binding of the client to the
execution of the service. In synchronous operations, the client will actually wait for the web
service to complete an operation. An example of this is probably a scenario wherein a database
read and write operation are being performed. If data is read from one database and
subsequently written to another, then the operations have to be done in a sequential manner.
Asynchronous operations allow a client to invoke a service and then execute other functions in
parallel. This is one of the common and probably the most preferred techniques for ensuring that
other services are not stopped when a particular operation is being carried out.
4. Ability to support Remote Procedure Calls (RPCs) - Web services enable clients to invoke
procedures, functions, and methods on remote objects using an XML-based protocol. Remote
procedures expose input and output parameters that a web service must support.
5. Supports Document Exchange - One of the key benefits of XML is its generic way of representing
not only data but also complex documents. These documents can be as simple as representing a
current address, or they can be as complex as representing an entire book.
15
SOA just makes it easier for software components over various networks to work with each other.
Web services which are built as per the SOA architecture tend to make web service more independent.
The web services themselves can exchange data with each other and because of the underlying
principles on which they are created, they don't need any sort of human interaction and also don't need
any code modifications. It ensures that the web services on a network can interact with each other
seamlessly.
16
8. Service Composability - Services break big problems into little problems. One should never
embed all functionality of an application into one single service but instead, break the service
down into modules each with a separate business functionality.
9. Service Interoperability - Services should use standards that allow diverse subscribers to use the
service. In web services, standards as XML and communication over HTTP is used to ensure it
conforms to this principle.
SOAP
In today's world, there are huge number of applications which are built on different programming
languages. For example, there could be a web application designed in Java, another in .Net and another
in PHP.
Exchanging data between applications is crucial in today's networked world. But data exchange between
these heterogeneous applications would be complex. So will be the complexity of the code to accomplish
this data exchange.
One of the methods used to combat this complexity is to use XML (Extensible Markup Language) as the
intermediate language for exchanging data between applications.
Every programming language has the capability to understand the XML markup language. Hence, XML
was used as the underlying medium for data exchange.
But there are no standard specifications on use of XML across all programming languages for data
exchange. That is where SOAP comes in.
SOAP was designed to work with XML over HTTP and have some sort of specification which could be
used across all applications. We will look into further details on the SOAP protocol in the subsequent
chapters.
The diagram below shows the various building blocks of a SOAP Message.
17
The SOAP message is nothing but a mere XML document which has the below components.
An Envelope element that identifies the XML document as a SOAP message – This is the
containing part of the SOAP message and is used to encapsulate all the details in the SOAP
message. This is the root element in the SOAP message.
A Header element that contains header information – The header element can contain information
such as authentication credentials which can be used by the calling application. It can also contain
the definition of complex types which could be used in the SOAP message. By default, the SOAP
message can contain parameters which could be of simple types such as strings and numbers,
but can also be a complex object type.
Suppose we wanted to send a structured data type which had a combination of a "Tutorial Name" and a
"Tutorial Description," then we would define the complex type as shown below.
18
The complex type is defined by the element tag <xsd:complexType>. All of the required elements of the
structure along with their respective data types are then defined in the complex type collection.
<xsd:complexType>
<xsd:sequence>
</xsd:sequence>
</xsd:complexType>
A Body element that contains call and response information – This element is what contains the
actual data which needs to be sent between the web service and the calling application. Below is
an example of the SOAP body which actually works on the complex type defined in the header
section. Here is the response of the Tutorial Name and Tutorial Description that is sent to the
calling application which calls this web service.
<soap:Body>
<GetTutorialInfo>
<TutorialName>Web Services</TutorialName>
</GetTutorialInfo>
</soap:Body>
Whenever a client application calls a method in the web service, the web service will automatically
generate a SOAP message which will have the necessary details of the data which will be sent from the
web service to the client application.
As discussed in the previous topic, a simple SOAP Message has the following elements –
Let's look at an example below of a simple SOAP message and see what element actually does.
19
1. As seen from the above SOAP message, the first part of the SOAP message is the envelope
element which is used to encapsulate the entire SOAP message.
2. The next element is the SOAP body which contains the details of the actual message.
3. Our message contains a web service which has the name of "Guru99WebService".
4. The "Guru99Webservice" accepts a parameter of the type 'int' and has the name of TutorialID.
Now, the above SOAP message will be passed between the web service and the client application.
You can see how useful the above information is to the client application. The SOAP message tells the
client application what is the name of the Web service, and also what parameters it expects and also
what is the type of each parameter which is taken by the web service.
REST stands for RE presentational State Transfer. REST is used to build Web services that are
lightweight, maintainable, and scalable in nature. A service which is built on the REST architecture is
called a RESTful service. The underlying protocol for REST is HTTP, which is the basic web protocol.
REST is a way to access resources which lie on a particular environment. For example, you could have a
server that could be hosting important documents or pictures or videos. All of these are an example of
resources. If a client, say a web browser needs any of these resources, it has to send a request to the
server to access these resources. Now REST defines a way on how these resources can be accessed.
1. Resources – The first key element is the resource itself. Let assume that a web application on a
server has records of several employees. Let's assume the URL of the web application
is http://demo.guru99.com. Now in order to access an employee record resource via REST, one
20
can issue the commandhttp://demo.guru99.com/employee/1 - This command tells the web server
to please provide the details of the employee whose employee number is 1.
2. Request Verbs - These describe what you want to do with the resource. A browser issues a GET
verb to instruct the endpoint it wants to get data. However there are many other verbs available
including things like POST, PUT, and DELETE. So in the case of the
example http://demo.guru99.com/employee/1 , the web browser is actually issuing a GET Verb
because it wants to get the details of the employee record.
3. Request Headers – These are additional instructions sent with the request. These might define
the type of response required or the authorization details.
4. Request Body - Data is sent with the request. Data is normally sent in the request when a POST
request is made to the REST web service. In a POST call, the client actually tells the web service
that it wants to add a resource to the server. Hence, the request body would have the details of
the resource which is required to be added to the server.
5. Response Body – This is the main body of the response. So in our example, if we were to query
the web server via the request http://demo.guru99.com/employee/1 , the web server might return
an XML document with all the details of the employee in the Response Body.
6. Response Status codes – These codes are the general codes which are returned along with the
response from the web server. An example is the code 200 which is normally returned if there is
no error when returning a response to the client.
The below diagram shows mostly all the verbs (POST, GET, PUT, and DELETE) and an example of what
they would mean.
1. POST – This would be used to create a new employee using the RESTful web service
2. GET - This would be used to get a list of all employee using the RESTful web service
3. PUT - This would be used to update all employee using the RESTful web service
4. DELETE - This would be used to delete all employee using the RESTful web service
Let's take a look from a perspective of just a single record. Let's say there was an employee record with
the employee number of 1.
21
1. POST – This would not be applicable since we are fetching data of employee 1 which is already
created.
2. GET - This would be used to get the details of the employee with Employee no as 1 using the
RESTful web service
3. PUT - This would be used to update the details of the employee with Employee no as 1 using the
RESTful web service
4. DELETE - This is used to delete the details of the employee with Employee no as 1
Restful Architecture
An application or architecture considered RESTful or REST-style has the following characteristics
1. State and functionality are divided into distributed resources – This means that every resource
should be accessible via the normal HTTP commands of GET, POST, PUT, or DELETE. So if
someone wanted to get a file from a server, they should be able to issue the GET request and get
the file. If they want to put a file on the server, they should be able to either issue the POST or
PUT request. And finally, if they wanted to delete a file from the server, they an issue the
DELETE request.
2. The architecture is client/server, stateless, layered, and supports caching –
Client-server is the typical architecture where the server can be the web server hosting the
application, and the client can be as simple as the web browser.
Stateless means that the state of the application is not maintained in REST.
22
For example, if you delete a resource from a server using the DELETE command, you cannot expect
that delete information to be passed to the next request.
In order to ensure that the resource is deleted, you would need to issue the GET request. The GET
request would be used to first get all the resources on the server. After which one would need to see if
the resource was actually deleted.
RESTFul Characteristics
The REST architecture is based on a few characteristics which are elaborated below. Any RESTful web
service has to comply with the below characteristics in order for it to be called RESTful. These
characteristics are also known as design principles which need to be followed when working with RESTful
based services.
1. Client-Server
This is the most fundamental requirement of a REST based architecture. It means that the server will
have a RESTful web service which would provide the required functionality to the client. The client send's
a request to the web service on the server. The server would either reject the request or comply and
provide an adequate response to the client.
2. Stateless
The concept of stateless means that its up to the client to ensure that all the required information is
provided to the server. This is required so that server can process the response appropriately. The server
should not maintain any sort of information between requests from the client. It's a very simple
independent question-answer sequence. The client asks a question, the server answers it appropriately.
The client will ask another question. The server will not remember the previous question-answer scenario
and will need to answer the new question independently.
3. Cache
23
The Cache concept is to help with the problem of stateless which was described in the last point. Since
each server client request is independent in nature, sometimes the client might ask the server for the
same request again. This is even though it had already asked for it in the past. This request will go to the
server, and the server will give a response. This increases the traffic across the network. The cache is a
concept implemented on the client to store requests which have already been sent to the server. So if the
same request is given by the client, instead of going to the server, it would go to the cache and get the
required information. This saves the amount of to and fro network traffic from the client to the server.
4. Layered System
The concept of a layered system is that any additional layer such as a middleware layer can be inserted
between the client and the actual server hosting the RESTFul web service (The middleware layer is
where all the business logic is created. This can be an extra service created with which the client could
interact with before it makes a call to the web service.). But the introduction of this layer needs to be
transparent so that it does not disturb the interaction between the client and the server.
5. Interface/Uniform Contract
This is the underlying technique of how RESTful web services should work. RESTful basically works on
the HTTP web layer and uses the below key verbs to work with resources on the server
SOAP – SOAP is a protocol which was designed before REST and came into the picture. The main idea
behind designing SOAP was to ensure that programs built on different platforms and programming
languages could exchange data in an easy manner.
REST – This was designed specifically for working with components such as media components, files, or
even objects on a particular hardware device. Any web service that is defined on the principles of REST
24
can be called a RestFul web service. A Restful service would use the normal HTTP verbs of GET, POST,
PUT and DELETE for working with the required components.
SOAP REST
SOAP stands for Simple Object REST stands for Representational State Transfer
Access protocol
SOAP is a protocol. SOAP was REST is an Architectural style in which a web service can only
designed with a specification. It be treated as a RESTful service if it follows the constraints of
includes a WSDL file which has the being
required information on what the web
service does in addition to the location 1. Client Server
of the web service. 2. Stateless
3. Cacheable
4. Layered System
5. Uniform Interface
SOAP cannot make use of REST REST can make use of SOAP as the underlying protocol for
since SOAP is a protocol and REST is web services, because in the end it is just an architectural
an architectural pattern. pattern.
SOAP uses service interfaces to REST use Uniform Service locators to access to the
expose its functionality to client components on the hardware device. For example, if there is
applications. In SOAP, the WSDL file an object which represents the data of an employee hosted on
provides the client with the necessary a URL as http://demo.guru99 , the below are some of URI that
information which can be used to can exist to access them
understand what services the web http://demo.guru99.com/Employee
SOAP requires more bandwidth for its REST does not need much bandwidth when requests are sent
usage. Since SOAP Messages to the server. REST messages mostly just consist of JSON
contain a lot of information inside of it, messages. Below is an example of a JSON message passed
25
the amount of data transfer using to a web server. You can see that the size of the message is
SOAP is generally a lot. comparatively smaller to SOAP.
<?xml version="1.0"?> {"city":"Mumbai","state":"Maharastra"}
<SOAP-ENV:Envelope
xmlns:SOAP-ENV
="http://www.w3.org/2001/12/soap-envel
ope"
SOAP-ENV:encodingStyle
=" http://www.w3.org/2001/12/soap-enco
ding">
<soap:Body>
<Demo.guru99WebService
xmlns="http://tempuri.org/">
<EmployeeID>int</EmployeeID>
</Demo.guru99WebService>
</soap:Body>
</SOAP-ENV:Envelope>
SOAP can only work with XML format. REST permits different data format such as Plain text, HTML,
As seen from SOAP messages, all XML, JSON, etc. But the most preferred format for transferring
data passed is in XML format. data is JSON.
Summary
One of the key differences between SOAP and REST is that SOAP is a protocol and REST is an
architectural pattern.
Other key differences between the SOAP and REST protocol is that the requests sent via REST
tend to be much lighter than SOAP. Because of this, applications don't require much bandwidth to
use REST web services over SOAP.
Security is another major concern with Web services and SOAP. REST is good when working with
web services open to the public, but if security is required, then the SOAP API has the necessary
implementation for the same.
26
REST has the ability to have a caching solution which will help save responses which have been
received from the server. In such cases, the client does not need to make the same request to the
server and can make use of the cache to get the desired response.
PHP Introduction
PHP scripts are executed on the web server and the result is sent to the
browser.
PHP gives you the freedom to add advanced features to your website.
PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.
The aim of this tutorial is to give you an easy, yet thorough and accurate introduction to PHP. It starts
from scratch but requires that you already have a good knowledge of HTML.
PHP can be used in many contexts – discussion forums, polls, shops, SMS gateways, mailing lists, etc.
The only limitation with what you choose to do with PHP is your imagination. PHP is not hard to learn, but
be aware that PHP is more sophisticated and demanding to learn than HTML. Therefore, patience in the
process is a virtue.
What is needed?
27
It is assumed that you already have a text editor and know how it is used.
Next, you need access to a computer or a server that can run PHP. In contrast to HTML and CSS, PHP
is not affected by which browser your visitors use, but by the type of server that's hosting your pages. This
is because PHP is a server-side technology.
In the next few lessons, you will learn all about how PHP works, and how to set up your computer to run
PHP. After that, you'll learn about specific functions and methods.
When you finish this tutorial, you will be able to code PHP and thus have access to unlimited possibilities
for adding interactivity to your webpages.
What is PHP
Whenever anyone is learning PHP, the most common questions that first come up are: What is PHP? And
how does it work?
It is precisely these questions we will look at in this lesson. It's a big help to understand such basics related
to PHP before you start developing you own PHP pages. Such basic understanding will increase the speed
of learning significantly.
So, let's get started!
What is PHP?
PHP stands for PHP: Hypertext Preprocessor
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
PHP was originally an acronym for Personal Home Pages, but is now a recursive acronym for
PHP: Hypertext Preprocessor.
PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and was subsequently
developed as open source. PHP is not a proper web standard – but an open-source technology. PHP is
neither real programming language – but PHP lets you use so-called scripting in your documents.
To describe what a PHP page is, you could say that it is a file with the extension .php that contains a
combination of HTML tags and scripts that run on a web server.
28
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can restrict users to access some pages on your website
PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP has support for a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
As you can see, the server simply sends an HTML file to the client. But if you instead
typehttp://www.mysite.com/page.php – and thus request an PHP page – the server is put to work:
29
The server first reads the PHP file carefully to see if there are any tasks that need to be executed. Only
when the server has done what it is supposed to do, the result is then sent to the client. It is important to
understand that the client only sees the result of the server's work, not the actual instructions.
This means that if you click "view source" on a PHP page, you do not see the PHP codes – only basic
HTML tags. Therefore, you cannot see how a PHP page is made by using "view source". You have to learn
PHP in other ways, for example, by reading this tutorial.
What you learn in this tutorial is to write commands to a server!
So, the first thing you need to get ahold of is… a server! But don't worry – you don't need to buy a new
computer. You just need to install some software on your computer that makes it function as a server.
Another option is to have a website on a hosted server that supports PHP. Then you just need to be online
while coding.
PHP Installation
30
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then install PHP and MySQL
Option 3: XAMPP
XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHP directly on our
computer without having to install PHP on our own.
Download XAMPP
Start by downloading XAMPP by following these links to download and installation guides:
Install XAMPP
Just follow the instructions on the screen during the installation process. Below are screenshots from an
installation on Windows.
1. Choose the "Installer" download on the XAMPP website:
31
2. Run the file and choose C:\xampp as the install location:
32
4. Click "Finish" when the installation process is complete:
When you have downloaded and installed XAMPP, you can start the server and save your future PHP
documents in the folder c:\xampp\htdocs on your computer and access them in the browser with the
address http://localhost.
Test
You can test whether XAMPP runs properly by following the steps below:
33
3. Create a file in Notepad (or similar text editor) named test.php (note that the file extension must be ".php"
instead of ".htm").
If the browser writes "Hello World!" the installation is successful, and you're ready to run PHP on your
computer. Otherwise, see below for how to fix common problems, see the XAMPP website for more
information.
If the Apache server won't start, it is probably because some other application is using port 80. Most likely
Skype or Microsoft IIS.
If you use Skype: start Skype, selecting Tools > Options > Connections and un-check the use of Port 80 as
an alternative port. Then close and re-start Skype.
If none of this helps, follow these steps to find the program that is using port 80:
34
1. Go to command prompt (Start > Run > cmd).
2. Type in: netstat -aon
3. You will see a list of IP numbers, port numbers and the process ID (PID).
4. Look for the row with 127.0.0.1:80 and remember the process ID.
5. Open up Task Manager (Start > Run > taskmgr).
6. Go to Process tab, click View > Select Columns…
7. Tick PID (Process Identifier)
8. Search the process that has the same process ID shown in netstat and close the program.
PHP Syntax
The PHP script is executed on the server, and the plain HTML result is sent back to the browser.
35
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that sends the text "Hello World!" back
to the browser:
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.
With PHP, there are two basic statements to output text in the browser: echo and print.
Comments in PHP
A comment is the portion of a program that exists only for the human reader and stripped out before
displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant to the local code.
Here are the examples of single line comments.
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
36
print "An example with single line comments";
?>
Multi-line comments: They are generally used for long explanations or notes, to write start the comment
with a slash followed by an asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like
this:
<?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!";
?>
Variables are used for storing values that can change over the course of a
script, whereas the constants are used for storing fixed values that doesn't
change.
Variables are used to store data, like text strings, numbers or arrays.
Important things to know about variables in PHP:
In PHP, a variable does not need to be declared before adding a value to it. PHP automatically
converts the variable to the correct data type, depending on its value.
After declaring a variable it can be reused throughout the code.
The assignment operator (=) used to assign value to a variable.
In PHP variable can be declared as: $var_name = value;
$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and the
variable x will hold the value 5.
37
Naming Conventions for PHP Variables
All variables in PHP start with a $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character "_".
A variable name cannot start with a number.
A variable name in PHP can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
A variable name cannot contain spaces.
Note: Variable names in PHP are case sensitive, it means $x and $X are two different variables. So be
careful while defining variable names.
The scope of a variable is the part of the script where the variable can be referenced/used.
1. local
2. global
3. static
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
This script will not produce any output because the echo statement refers to a local version of
the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little
bit different from the C language in that global variables in C are automatically available to functions
unless specifically overridden by a local definition. This can cause some problems in that people may
38
inadvertently change a global variable. In PHP global variables must be declared global inside a function
if they are going to be used in that function.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The above script will output 3. By declaring $a and $b global within the function, all references to either
variable will refer to the global version. There is no limit to the number of global variables that can be
manipulated by a function.
Another important feature of variable scoping is the static variable. A static variable exists only in a local
function scope, but it does not lose its value when program execution leaves this scope. Consider the
following example:
<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
?>
This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which
increments the variable serves no purpose since as soon as the function exits the $a variable disappears.
To make a useful counting function which will not lose track of the current count, the $a variable is
declared static:
39
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Now, $a is initialized only in first call of function and every time the test() function is called it will print the
value of $a and increment it.
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script. A constant is case-sensitive by default. By convention, constant
identifiers are always uppercase.
Syntax:
You can define a constant by using the define()-function or by using the const keyword outside a class
definition as of PHP 5.3.0. Once a constant is defined, it can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants prior to PHP 5.6. From
PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to
define an array constant.
You can get the value of a constant by simply specifying its name. Unlike with variables, you
should not prepend a constant with a $.
40
Example #1 Defining Constants
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>
<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';
echo CONSTANT;
// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>
PHP supports total eight primitive data types: Integer, Floating point
number or Float, String, Booleans, Array, Object, resource and NULL.
The values assigned to a PHP variable may be of different data types including simple string and numeric
types to more complex data types like arrays and objects. PHP supports total eight data types which are
used to construct variables.
41
boolean
integer
float (floating-point number, double)
string
array
object
resource
NULL
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.
if (TRUE)
else
Here are the rules for determine the "truth" of any value not already of the Boolean type:
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the string "0",
and is true otherwise.
If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
42
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
$true_num = 3 + 0.14159;
$false_array = array();
$false_null = NULL;
$false_str = "";
Integers
Syntax
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2)
notation, optionally preceded by a sign (- or +).
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the
number with 0x. To use binary notation precede the number with 0b.
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
43
Integer overflow
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as
a float instead. Also, an operation which results in a number beyond the bounds of the integer type will
return a float instead.
<?php
$large_number = 2147483647;
var_dump($large_number); // int(2147483647)
$large_number = 2147483648;
var_dump($large_number); // float(2147483648)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number); // float(50000000000)
?>
<?php
$large_number = 9223372036854775807;
var_dump($large_number); // int(9223372036854775807)
$large_number = 9223372036854775808;
var_dump($large_number); // float(9.2233720368548E+18)
$million = 1000000;
$large_number = 50000000000000 * $million;
var_dump($large_number); // float(5.0E+19)
?>
There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to
an integer to round it towards zero, or the round() function provides finer control over rounding.
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
44
Floating point numbers
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any
of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Strings
A string is series of characters, where a character is the same as a byte. This means that PHP only
supports a 256-character set, and hence does not offer native Unicode support.
Syntax
single quoted
double quoted
heredoc syntax
nowdoc syntax (since PHP 5.3.0)
Single quoted
The simplest way to specify a string is to enclose it in single quotes (the character ').
<?php
echo 'this is a simple string';
45
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special
characters:
Escaped characters
echo "this will display \$ sign"; //output: this will display $ sign
As in single quoted strings, escaping any other character will result in the backslash being printed too.
Before PHP 5.1.1, the backslash in \{$var} had not been printed.
The most important feature of double-quoted strings is the fact that variable names will be expanded
Heredoc
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is
provided, then a newline. The string itself follows, and then the same identifier again to close the
quotation.
46
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same
naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores,
and must start with a non-digit character or underscore.
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<foot
<br>
foot;
<?php
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
Output
My name is "MyName". I am printing some Foo.
47
Now, I am printing some Bar2.
This should print a capital 'A': A
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified
similarly to a heredoc, but no parsing is done inside a nowdoc.
A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is
enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc
identifiers.
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
<?php
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
EOT;
?>
48
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it
like this:
<?php
$a = NULL;
var_dump($a);
echo "<br>";
?>
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as
well have typed:
A variable that has been assigned NULL has the following properties:
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
Syntax
An array can be created using the array() language construct. It takes any number of comma-
separated key => value pairs as arguments.
array(
...
The comma after the last array element is optional and can be omitted. This is usually done for single-line
arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing
comma is commonly used, as it allows easier addition of new elements at the end.
49
<?php
var_dump($colors);
echo "<br>";
$color_codes = array(
);
var_dump($color_codes);
echo "<br>";
?>
Objects
An object is a data type that not only allows storing data but also information on, how to process that
data. An object is a specific instance of a class which serve as templates for objects. Objects are
created based on this template via the new keyword.
Here's a simple example of a class definition followed by the object creation.
<?php
// Class definition
class greeting{
// properties
// methods
function show_greeting(){
return $this->str;
50
$message = new greeting;
var_dump($message);
?>
Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections.
<?php
var_dump($handle);
echo "<br>";
var_dump($link);
?>
PHP Operators
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Increment/Decrement Operators
String Operators
51
Array Operators
5%2 1
Remainder of x divided
x%y Modulus 10 % 8 2
by y
10 % 2 0
–x Negation Opposite of x –2
1. <?php
2. $x = 10;
3. $y = 4;
9. ?>
52
The left operand gets set to the value of the expression on
x=y x=y
the right
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
<?php
53
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
54
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
x=6
True if either or both x and y y=3
x or y Or
are true (x==6 or y==5) returns
true
x=6
True if either x or y is true, but y=3
x xor y Xor
not both (x==6 xor y==3) returns
false
x=6
y=3
x && y And True if both x and y are true
(x < 10 && y > 1) returns
true
x=6
True if either or both x and y y=3
x || y Or
are true (x==5 || y==5) returns
false
x=6
!x Not True if x is not true y=3
!(x==y) returns true
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
55
?>
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Concatenation
x .= y Append the $str2 to the $str1 $str1 .= $str2
Assignment
1. <?php
2. $x = "Hello";
3. $y = " World!";
56
4. echo $x . $y; // Outputs: Hello World!
5.
6. $x .= $y;
7. echo $x; // Outputs: Hello World!
8. ?>
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a
loop, a conditional statement or even a statement that does nothing (an empty statement). Statements
usually end with a semicolon. In addition, statements can be grouped into a statement-group by
encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.
if
else
elseif/else if
Alternative syntax for control structures
while
do-while
for
foreach
break
continue
switch
declare
return
require
include
require_once
include_once
goto
57
switch statement – selects one of many blocks of code to be executed
The if Statement
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time is less than 20: Example:
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
Output:
Have a good day!
Syntax
if (condition)
else
58
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output
"Have a nice day!”
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
else
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed within
curly braces:
<html>
<body>
<?php
$d=date("D");
59
if ($d=="Fri")
?>
</body>
</html>
Syntax
if (condition)
elseif (condition)
else
60
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice
Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!”
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
elseif ($d=="Sun")
else
?>
</body>
</html>
61
switch (expression)
case label1:
break;
case label2:
break;
default:
code to be executed
if expression is different
The switch statement works in an unusual way. First it evaluates given expression then seeks a label to
match the resulting value. If a matching value is found then the code associated with the matching label will
be executed or if none of the labels match then statement will execute any specified default code.
<html>
<body>
<?php
62
$d=date("D");
switch ($d)
case "Mon":
break;
case "Tue":
break;
case "Wed":
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
63
break;
case "Sun":
break;
default:
?>
</body>
</html>
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch.
In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the
closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the
alternative syntax. The HTML block would be displayed only if $a is equal to 5.
The alternative syntax applies to else and elseif as well. The following is an if structure
with elseif and else in the alternative format:
<?php
if ($a == 5):
echo "a equals 5";
64
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
?>
Note:
Warning
Any output (including whitespace) between a switch statement and the first case will result in a syntax
error. For example, this is invalid:
Whereas this is valid, as the trailing newline after the switch statement is considered part of the
closing ?> and hence nothing is output between the switch and case:
65
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead
of adding several almost equal lines in a script we can use loops to perform a task like this.
while (condition)
{
code to be executed;
}
//or
while (expr):
statement
...
endwhile;
The following examples are identical, and both print the numbers 1 through 10:
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
66
echo $i;
$i++;
endwhile;
?>
do
{
code to be executed;
}
while (condition);
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
67
for (init; condition; increment)
{
code to be executed;
}
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the beginning of
the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the end
of the iteration)
Note: The init and increment parameters above can be empty or have multiple expressions (separated by
commas).
Consider the following examples. All of them display the numbers 1 through 10:
<?php
/* example 1 */
/* example 2 */
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
68
PHP also supports the alternate "colon syntax" for for loops.
statement
...
endfor;
statement
statement
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer
is moved by one) – so on the next loop iteration, you'll be looking at the next array value.
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Output:
one
two
three
69
break
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to
be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.
<?php
continue
continue is used within looping structures to skip the rest of the current loop iteration and continue
execution at the condition evaluation and then the beginning of the next iteration.
Note: In PHP the switch statement is considered a looping structure for the purposes
of continue. continue behaves like break (when no arguments are passed). If a switch is inside a
loop, continue 2 will continue with the next iteration of the outer loop.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should
skip to the end of. The default value is 1, thus skipping to the end of the current loop.
<?php
$x = 1;
echo ‘List of odd numbers between 1 to 10’;
while ($x <= 10
{
if (($x % 2) == 0)
{
$x++;
continue;
}
else
{
echo $x;
70
$x++;
}
}
Output:
List of odd numbers between 1 to 10
1
3
5
7
9
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be
reused on multiple pages. This will help developers to make it easy to change the layout of complete website
with minimal effort. If there is any change required then instead of changing thousands of files just change
included file.
Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
The basic syntax of the include() and require() statement can be given with:
Syntax:
include 'filename';
Assume that you have a standard header file, called "header.php". To include the header file in a page, use
include/require:
<html>
<body>
71
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
<?php
$color='red';
$car='BMW';
?>
<html>
<body>
</body>
</html>
Assume you want to create a common menu for your website. Then create a file menu.php with the following
content.
<a href="http://www.mytoptutorials.com/">Home</a> –
<a href="http://www.mytoptutorials.com/html/">HTML</a> –
<a href="http://www.mytoptutorials.com/php/">PHP</a> – <br />
Now create as many pages as you like and include this file to create header. For example now your test.php
file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
72
Home – HTML – PHP
This is an example to show how to include PHP file. You can include mean.php
file in as many as files you like!
So there is no difference in require() and include() except they handle error conditions. It is recommended
to use the require() function instead of include(), because scripts should not continue executing if files are
missing or misnamed.
Syntax:
require 'filename';
You can try using above example with require() function and it will generate same result. But if you will try
following two examples where file does not exist then you will get different results.
<html>
<body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
NOTE: You may get plain warning messages or fatal error messages or nothing at all. This depends on
your PHP Server configuration.
73
goto
The goto operator can be used to jump to another section in the program. The target point is specified by
a label followed by a colon, and the instruction is given as goto followed by the desired target label. This
is not a full unrestricted goto. The target label must be within the same file and context, meaning that you
cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of
loop or switch structure.
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
<?php
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
?>
j hit 17
<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
loop:
}
}
echo "$i = $i";
?>
script on line 2
74
PHP Functions
Table of Contents
PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts
to perform a specific task, like gettype(), print_r(), var_dump, etc.
User-defined functions
In addition to the built-in function, PHP also allows you to define your own functions. It is a way to create
reusable code packages that perform specific tasks and can be kept and maintained separately form
main program. Here are some advantages of using functions:
Functions reduces the repetition of code within a program — Function allows you to extract
commonly used block of code into a single component. Now can you can perform the same task
by calling this function wherever you want without having to copy and paste the same block of
code again and again.
Functions makes the code much easier to maintain — Since a function created once can be
used many times, so any changes made inside a function automatically implemented at all the
places without touching the several files.
Functions makes it easier to eliminate the errors — When the program is subdivided into
functions, if any error occur you know exactly what function causing the error and where to find it.
Functions can be reused in other application — Because a function is separated from the rest
of the script, it's easy to reuse the same function in other applications just by including the php file
containing those functions.
75
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
Example #1
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
<?php
$makefoo = true;
bar();
if ($makefoo) {
76
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
?>
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
foo();
bar();
?>
All functions and classes in PHP have the global scope - they can be called outside a function even if
they were defined inside and vice versa.
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared
functions.
Note: Function names are case-insensitive, though it is usually good form to call functions as they appear
in their declaration.
77
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>
You can specify parameters when you define your function to accept input values at run time. The
parameters work like placeholder variables within a function; they're replaced at run time by the values
(known as argument) provided to the function at the time of invocation.
You can define as many parameters as you like. However for each parameter you specify, a
corresponding argument needs to be passed to the function when it is called.
The getSum() function in following example takes two integer values as arguments, simply add them
together and then display the result in the browser.
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
You can also create functions with optional parameters — just insert the parameter name, followed by an
equals (=) sign, followed by a default value, like this.
78
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
As you can see the third call to customFont() doesn't include the second argument. This causes PHP
engine to use the default value for the $size parameter which is 1.5.
Function arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of
expressions. The arguments are evaluated from left to right.
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to modify its
arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the
argument name in the function definition:
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
79
echo $str; // outputs 'This is a string, and something extra.'
?>
A function may define C++-style default values for scalar arguments as follows:
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Output:
Making a cup of .
PHP also allows the use of arrays and the special type NULL as default values, for example:
<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>
The default value must be a constant expression, not (for example) a variable, a class member or a
function call.
Note that when using default arguments, any defaults should be on the right side of any non-default
arguments; otherwise, things will not work as expected. Consider the following code snippet:
80
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}
Output:
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}
Returning values
Values are returned by using the optional return statement. Any type may be returned, including arrays
and objects. This causes the function to end its execution immediately and pass control back to the line
from which it was called. See return for more information.
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // outputs '16'.
?>
81
A function cannot return multiple values, but similar results can be obtained by returning an array.
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses
appended to it, PHP will look for a function with the same name as whatever the variable evaluates to,
and will attempt to execute it. Among other things, this can be used to implement callbacks, function
tables, and so forth.
<?php
function foo() {
echo "In foo()<br />\n";
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
82
Object methods can also be called with the variable functions syntax.
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
?>
Anonymous functions
The function that does not possess any name are called anonymous functions.
Such functions are created using create_function( ) built-in function. Anonymous functions are also called
as lambda functions.
<?php
$fname=create_function('$a,$b',
'$c = $a + $b;
return $c;');
echo $fname(10,20);
?>
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
83
PHP Strings
A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all.
PHP provides many built-in functions for manipulating strings like calculating the length of a string, find
substrings or characters, replacing part of a string with different characters, take a string apart, and many
others. Here are the examples of some of these functions.
The strlen() function is used to calculate the number of characters inside a string. It also includes the
blank spaces inside the string.
1. <?php
3.
4. // Outputs: 28
5. echo strlen($my_str);
6. ?>
1. <?php
2. $my_str = 'The quick brown fox jumps over the lazy dog.';
3.
4. // Outputs: 9
5. echo str_word_count($my_str);
84
6. ?>
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
?>
Output:
1. <?php
2. $my_str = 'If the facts do not fit the theory, change the facts.';
3.
6.
9. ?>
Output:
The text was replaced 2 times.
Reversing a String
The strrev() function reverses a string.
85
1. <?php
3.
5. echo strrev($my_str);
6. ?>
Output:
.gnihtyreve ton tub ,gnihtyna od nac uoY
String Functions
The following string functions are the part of the PHP core so you can use these functions within your
script without any further installation.
Function Description
addslashes() Returns a string with backslashes before the characters that need to be
escaped. These characters are single quote ('), double quote ("), backslash (\)
and NULL
chop() Strip whitespace (or other characters) from the end of a string. Alias of rtrim()
86
Function Description
hebrevc() Convert logical Hebrew text to visual text with newline conversion
implode() Return a string by joining the elements of an array with a specified string
ltrim() Removes whitespace (or other characters) from the beginning of a string
87
Function Description
rtrim() Removes whitespace (or other characters) from the end of a string
str_ireplace() Replace all occurrences of the search string with the replacement string. Case-
insensitive version ofstr_replace().
88
Function Description
str_replace() Replace all occurrences of the search string with the replacement string (case-
sensitive)
strchr() Finds the first occurrence of a string inside another string. Alias of strstr()
strcspn() Returns the number of characters found in a string before any part of some
specified characters are found
stristr() Finds the first occurrence of a string inside another string (case-insensitive).
Case-insensitive version of strstr()
89
Function Description
strripos() Find the position of the last occurrence of a string inside another string (case-
insensitive)
strrpos() Find the position of the last occurrence of a string inside another string (case-
sensitive)
strspn() Returns the number of characters found in a string that contains only
characters from a specified charlist
strstr() Find the first occurrence of a string inside another string (case-sensitive)
substr_compare() Compares of two strings from a specified start position up to the length of the
comparison. The comparison is binary safe and optionally case-sensitive
90
Function Description
trim() Removes whitespace (or other characters) from the beginning and end of a
string
PHP Arrays
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look
like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars,
but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.
There are three different kind of arrays and each array value is accessed using an ID c which is called array
index.
Indexed array – An array with a numeric index. Values are stored and accessed in linear
fashion
91
Associative array – An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.
Multidimensional array – An array containing one or more arrays and values are accessed
using multiple indices
array();
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Value is 1
Value is 2
92
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output Result:
3
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Output Result:
Volvo
BMW
Toyota
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in
terms of their index. Associative array will have their index as string so that you can establish a strong
association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice.
Instead, we could use the employees names as the keys in our associative array, and the value would be
their respective salary.
93
NOTE: Don't keep associative array inside double quote while printing otherwise it would not return any
value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);
echo "Salary of mohammad is ". $salaries[‘mohammad’] . "<br />";
echo "Salary of qadir is ". $salaries[‘qadir’]. "<br />";
echo "Salary of zara is ". $salaries[‘zara’]. "<br />";
/* Second method to create array. */
$salaries[‘mohammad’] = "high";
$salaries[‘qadir’] = "medium";
$salaries[‘zara’] = "low";
echo "Salary of mohammad is ". $salaries[‘mohammad’] . "<br />";
echo "Salary of qadir is ". $salaries[‘qadir’]. "<br />";
echo "Salary of zara is ". $salaries[‘zara’]. "<br />";
?>
</body>
</html>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
94
}
?>
Output Result:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in the
sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple
index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks[‘mohammad’][‘physics’] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks[‘qadir’][‘maths’] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks[‘zara’][‘chemistry’] . "<br />";
95
?>
</body>
</html>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
Output Result:
BMW
Toyota
Volvo
The following example sorts the elements of the $numbers array in ascending numerical order:
96
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>
Output Result:
2
4
6
11
22
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Output Result:
Volvo
Toyota
BMW
The following example sorts the elements of the $numbers array in descending numerical order:
<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>
Output Result:
22
11
6
4
2
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
97
asort($age);
?>
Output Result:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
Output Result:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Output Result:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
Output Result:
98
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
$last_names = array_column($a,
'last_name');
print_r($last_names);
?>
99
elements from one "keys"
array and one "values" array. $c=array_combine($fname,$age);
print_r($c);
?>
The array_diff_assoc()
array_diff_assoc() function compares the keys <?php
and values of two (or more) $a1=array("a"=>"red","b"=>"green","c"=>"bl
arrays, and returns the ue","d"=>"yellow");
differences. $a2=array("a"=>"red","b"=>"green","c"=>"bl
This function compares the ue");
keys and values of two (or
more) arrays, and return an $result=array_diff_assoc($a1,$a2);
array that contains the entries print_r($result);
from array1 that are not ?>
present in array2 or array3,
etc.
The array_diff_uassoc()
array_diff_uassoc() function compares the keys <?php
and values of two (or more) function myfunction($a,$b)
arrays, and returns the {
differences. if ($a===$b)
100
Note: This function uses a {
user-defined function to return 0;
compare the keys! }
This function compares the return ($a>$b)?1:-1;
keys and values of two (or }
more) arrays, and return an
array that contains the entries $a1=array("a"=>"red","b"=>"green","c"=>"bl
from array1 that are not ue");
present in array2 or array3, $a2=array("d"=>"red","b"=>"green","e"=>"bl
etc. ue");
$result=array_diff_uassoc($a1,$a2,"myfunc
tion");
print_r($result);
?>
The array_diff_ukey() function the keys of two arrays (using a user-
array_diff_ukey() compares the keys of two (or defined key comparison function), and
more) arrays, and returns the return the differences:
differences.
Note: This function uses a <?php
user-defined function to function myfunction($a,$b)
compare the keys! {
This function compares the if ($a===$b)
keys of two (or more) arrays, {
and return an array that return 0;
contains the entries }
from array1 that are not return ($a>$b)?1:-1;
present in array2 or array3, }
etc.
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_diff_ukey($a1,$a2,"myfunctio
n");
print_r($result);
?>
101
This function passes each {
value of the input array to the return($var & 1);
callback function. If the }
callback function returns true,
the current value from input is $a1=array("a","b",2,3,4);
returned into the result array. print_r(array_filter($a1,"test_odd"));
Array keys are preserved. ?>
The array_intersect_assoc()
array_intersect_assoc() function compares the keys <?php
and values of two (or more) $a1=array("a"=>"red","b"=>"green","c"=>"bl
arrays, and returns the ue","d"=>"yellow");
matches. $a2=array("a"=>"red","b"=>"green","c"=>"bl
This function compares the ue");
keys and values of two or
more arrays, and return an $result=array_intersect_assoc($a1,$a2);
array that contains the entries print_r($result);
from array1 that are present ?>
in array2, array3, etc.
The array_intersect_key()
array_intersect_key() function compares the <?php
keys of two (or more) arrays, $a1=array("a"=>"red","b"=>"green","c"=>"bl
and returns the matches. ue");
This function compares the $a2=array("a"=>"red","c"=>"blue","d"=>"pin
keys of two or more arrays, k");
and return an array that
contains the entries $result=array_intersect_key($a1,$a2);
from array1 that are present print_r($result);
inarray2, array3, etc. ?>
The array_intersect_uassoc()
array_intersect_uassoc() function compares the keys <?php
and values of two (or more) function myfunction($a,$b)
102
arrays, and returns the {
matches. if ($a===$b)
Note: This function uses a {
user-defined function to return 0;
compare the keys! }
This function compares the return ($a>$b)?1:-1;
keys and values of two or }
more arrays, and return an
array that contains the entries $a1=array("a"=>"red","b"=>"green","c"=>"bl
from array1 that are present ue");
in array2, array3, etc. $a2=array("d"=>"red","b"=>"green","e"=>"bl
ue");
$result=array_intersect_uassoc($a1,$a2,"m
yfunction");
print_r($result);
?>
The array_intersect_ukey()
array_intersect_ukey() function compares the <?php
keys of two (or more) arrays, function myfunction($a,$b)
and returns the matches. {
Note: This function uses a if ($a===$b)
user-defined function to {
compare the keys! return 0;
This function compares the }
keys of two or more arrays, return ($a>$b)?1:-1;
and return an array that }
contains the entries
from array1 that are present $a1=array("a"=>"red","b"=>"green","c"=>"bl
inarray2, array3, etc. ue");
$a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_intersect_ukey($a1,$a2,"myf
unction");
print_r($result);
?>
The array_key_exists()
array_key_exists() function checks an array for a <?php
specified key, and returns $a=array("Volvo"=>"XC90","BMW"=>"X5");
true if the key exists and false if (array_key_exists("Volvo",$a))
if the key does not exist. {
Tip: Remember that if you echo "Key exists!";
skip the key when you specify }
an array, an integer key is else
generated, starting at 0 and {
increases by 1 for each value. echo "Key does not exist!";
(See example 2) }
?>
103
print_r(array_keys($a));
?>
104
The array_pop() function
array_pop() deletes the last element of an <?php
array. $a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
105
The
array_replace_recursive() array_replace_recursive() <?php
function replaces the values $a1=array("a"=>array("red"),"b"=>array("gr
of the first array with the een","blue"),);
values from following arrays $a2=array("a"=>array("yellow"),"b"=>array("
recursively. black"));
Tip: You can assign one array print_r(array_replace_recursive($a1,$a2));
to the function, or as many as ?>
you like.
If a key from array1 exists in
array2, values from array1
will be replaced by the values
from array2. If the key only
exists in array1, it will be left
as it is. If a key exist in array2
and not in array1, it will be
created in array1. If multiple
arrays are used, values from
later arrays will overwrite the
previous ones.
Note: If you do not specify a
key for each array, this
function will behave exactly
the same as
the array_replace() function.
106
Note: If the array have string print_r(array_slice($a,2));
keys, the returned array will ?>
always preserve the keys
(See example 4).
$result=array_udiff($a1,$a2,"myfunction");
print_r($result);
?>
The array_udiff() function
array_udiff() compares the keys and <?php
values of two or more arrays, function myfunction($a,$b)
and returns the differences. {
Note: This function uses a if ($a===$b)
built-in function to compare {
the keys, and a user-defined return 0;
function to compare the }
values! return ($a>$b)?1:-1;
This function compares the }
keys and values of two (or
more) arrays, and return an $a1=array("a"=>"red","b"=>"green","c"=>"bl
array that contains the entries ue");
from array1that are not $a2=array("a"=>"red","b"=>"blue","c"=>"gre
present en");
in array2 or array3, etc.
$result=array_udiff_assoc($a1,$a2,"myfunc
107
tion");
print_r($result);
?>
The array_udiff() function
array_udiff() compares the keys and <?php
values of two or more arrays, function myfunction($a,$b)
and returns the differences. {
Note: This function uses a if ($a===$b)
built-in function to compare {
the keys, and a user-defined return 0;
function to compare the }
values! return ($a>$b)?1:-1;
This function compares the }
keys and values of two (or
more) arrays, and return an $a1=array("a"=>"red","b"=>"green","c"=>"bl
array that contains the entries ue");
from array1that are not $a2=array("a"=>"red","b"=>"blue","c"=>"gre
present en");
in array2 or array3, etc.
$result=array_udiff_assoc($a1,$a2,"myfunc
tion");
print_r($result);
?>
The array_udiff_uassoc()
array_udiff_uassoc() function compares the keys <?php
and values of two or more function myfunction_key($a,$b)
arrays, and returns the {
differences. if ($a===$b)
Note: This function {
uses two user-defined return 0;
functions for comparison; the }
key is used in the first return ($a>$b)?1:-1;
function and the value is used }
in the second!
This function compares the function myfunction_value($a,$b)
keys and values of two (or {
more) arrays, and return an if ($a===$b)
array that contains the entries {
from array1that are not return 0;
present }
in array2 or array3, etc. return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","b"=>"green","c"=>"gr
een");
$result=array_udiff_uassoc($a1,$a2,"myfun
ction_key","myfunction_value");
print_r($result);
?>
The array_uintersect()
array_uintersect() function compares the <?php
function myfunction($a,$b)
108
values of two or more arrays, {
and returns the matches. if ($a===$b)
Note: This function uses a {
user-defined function to return 0;
compare the values! }
This function compares the return ($a>$b)?1:-1;
values of two (or more) }
arrays, and return an array
that contains the entries $a1=array("a"=>"red","b"=>"green","c"=>"bl
from array1 that are present ue");
in array2, array3, etc. $a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_uintersect($a1,$a2,"myfuncti
on");
print_r($result);
?>
The array_uintersect_assoc()
array_uintersect_assoc() function compares the keys <?php
and values of two or more function myfunction($a,$b)
arrays, and returns the {
matches. if ($a===$b)
Note: This function uses a {
built-in function to compare return 0;
the keys, and a user-defined }
function to compare the return ($a>$b)?1:-1;
values! }
This function compares the
keys and values of two (or $a1=array("a"=>"red","b"=>"green","c"=>"bl
more) arrays, and return an ue");
array that contains the entries $a2=array("a"=>"red","b"=>"blue","c"=>"gre
from array1that are present en");
in array2, array3, etc.
$result=array_uintersect_assoc($a1,$a2,"m
yfunction");
print_r($result);
?>
The
array_uintersect_uassoc() array_uintersect_uassoc() <?php
function compares the keys function myfunction_key($a,$b)
and values of two or more {
arrays, and returns the if ($a===$b)
matches. {
Note: This function return 0;
uses two user-defined }
functions for comparison; the return ($a>$b)?1:-1;
key is used in the first }
function and the value is used
in the second! function myfunction_value($a,$b)
This function compares the {
keys and values of two (or if ($a===$b)
more) arrays, and return an {
array that contains the entries return 0;
from array1that are present }
in array2, array3, etc. return ($a>$b)?1:-1;
109
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","b"=>"green","c"=>"gr
een");
$result=array_uintersect_uassoc($a1,$a2,"
myfunction_key","myfunction_value");
print_r($result);
?>
The array_unique() function
array_unique() removes duplicate values <?php
from an array. If two or more $a=array("a"=>"red","b"=>"green","c"=>"red
array values are the same, ");
the first appearance will be print_r(array_unique($a));
kept and the other will be ?>
removed.
Note: The returned array will
keep the first array item's key
type.
110
array_walk_recursive() The array_walk_recursive() <?php
function runs each array function myfunction($value,$key)
element in a user-defined {
function. The array's keys and echo "The key $key has the value
values are parameters in the $value<br>";
function. The difference }
between this function and $a1=array("a"=>"red","b"=>"green");
thearray_walk() function is $a2=array($a1,"1"=>"blue","2"=>"yellow");
that with this function you can array_walk_recursive($a2,"myfunction");
work with deeper arrays (an ?>
array inside an array).
print_r($result);
?>
111
end() - moves the
internal pointer to,
and outputs, the last
element in the array
next() - moves the
internal pointer to,
and outputs, the next
element in the array
prev() - moves the
internal pointer to,
and outputs, the
previous element in
the array
reset() - moves the
internal pointer to the
first element of the
array
each() - returns the
current element key
and value, and
moves the internal
pointer forward
112
pos() The pos() function returns the <?php
value of the current element $people = array("Peter", "Joe", "Glenn",
in an array. "Cleveland");
This function is an alias of echo pos($people) . "<br>";
the current() function. ?>
Every array has an internal
pointer to its "current"
element, which is initialized to
the first element inserted into
the array.
$arr=array("a"=>4,"b"=>2,"c"=>8,d=>"6");
uasort($arr,"my_sort");
?>
The uksort() function sorts an
uksort() array by keys using a user- <?php
defined comparison function. function my_sort($a,$b)
Tip: Use the uasort() function {
to sort an array by values if ($a==$b) return 0;
using a user-defined return ($a<$b)?-1:1;
comparison function. }
113
$arr=array("a"=>4,"b"=>2,"c"=>8,d=>"6");
uksort($arr,"my_sort");
?>
$a=array(4,2,8,6);
usort($a,"my_sort");
?>
The shuffle() function
shuffle() randomizes the order of the <?php
elements in the array. $my_array =
This function assigns new array("red","green","blue","yellow","purple");
keys for the elements in the
array. Existing keys will be shuffle($my_array);
removed (See Example 1 print_r($my_array);
below). ?>
The HTTP GET and POST methods are used to send information to
server.
In GET method the data is sent as URL parameters that are usually strings of name and value pairs
separated by ampersands (&). In general, a URL with GET data will look like this:
http://www.example.com/action.php?name=john&age=24
The bold parts in the URL are the GET parameters and the italic parts are the value of those parameters.
More than one parameter=value can be embedded in the URL by concatenating with ampersands (&).
One can only send simple text data via GET method.
114
Advantages and Disadvantages of Using the GET Method
Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the
page with specific query string values.
The GET method is not suitable for passing sensitive information such as the username and
password, because these are fully visible in the URL query string as well as potentially stored in
the client browser's memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL is
limited. So, there is a limitation for the total data to be sent.
PHP provides the superglobal variable $_GET to access all the information sent either through the URL
or submitted through an HTML form using the method="get".
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_GET["name"])){
}
?>
<label for="inputName">Name:</label>
</form>
</body>
115
Advantages and Disadvantages of Using the POST Method
It is more secure than GET because user-entered information is never visible in the URL query string
or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as
well as binary data (uploading a file) using POST.
Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark
the page with specific query.
Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via
post method or submitted through an HTML form using the method="post".
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_POST["name"])){
}
?>
<label for="inputName">Name:</label>
</form>
</body>
PHP provides another superglobal variable $_REQUEST that contains the values of both
the$_GET and $_POST variables as well as the values of the $_COOKIE superglobal variable.
116
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_REQUEST["name"])){
}
?>
<label for="inputName">Name:</label>
</form>
</body>
You will learn more about PHP cookies and form handling in advanced section
Note: The superglobal variables $_GET, $_POST and $_REQUEST are built-in variables that are always
available in all scopes throughout a script.
117