Vous êtes sur la page 1sur 118

2016

PHP BASIC

PHP TUTORIAL FOR BEGINNERS


BY: MIRWAIS FARAHI

SOFTWARE HOUSE, COMPUTER SCIENCE FACULTY, RANA UNIVERSITY


[Blank Page]

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.

Web service architecture & Introduction


Modern day business applications use variety of programming platforms to develop web-based
applications. Some applications may be developed in Java, others in .Net, while some other in Angular
JS, Node.js, etc.

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.

What are web services


A web service is a software module which is designed to perform a certain set of tasks.

 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.

Let's look at these components in more detail.

SOAP (Simple Object Access Protocol)

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.

Here is what a SOAP message consists of

 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.

An example of a WSDL file is given below.

<definitions>

<message name="TutorialRequest">

<part name="TutorialID" type="xsd:string"/>

</message>

<message name="TutorialResponse">

<part name="TutorialName" type="xsd:string"/>

</message>

<portType name="Tutorial_PortType">

<operation name="Tutorial">

<input message="tns:TutorialRequest"/>

<output message="tns:TutorialResponse"/>

</operation>

</portType>

<binding name="Tutorial_Binding" type="tns:Tutorial_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.

Why web services


We already understand why web services came about in the first place, which was to provide a platform
which could allow different applications to talk to each other.

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.

Web service Characteristics


Web services have the following special behavioral characteristics:

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.

SOA (Service Oriented Architecture) Principles


A service-oriented architecture (SOA) is an architectural pattern in computer software design in which
application components provide services to other components via a communications protocol, typically
over a network. The principles of service-orientation are independent of any product, vendor or
technology.

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.

SOA is based on some key principles which are mentioned below

1. Standardized Service Contract - Services adhere to a service-description. A service must have


some sort of description which describes what the service is about. This makes it easier for client
applications to understand what the service does.
2. Loose Coupling – Less dependency on each other. This is one of the main characteristics of web
services which just states that there should be as less dependency as possible between the web
services and the client invoking the web service. So if the service functionality changes at any
point in time, it should not break the client application or stop it from working.
3. Service Abstraction - Services hide the logic they encapsulate from the outside world. The service
should not expose how it executes its functionality; it should just tell the client application on what
it does and not on how it does it.
4. Service Reusability - Logic is divided into services with the intent of maximizing reuse. In any
development company re-usability is a big topic because obviously one wouldn't want to spend
time and effort building the same code again and again across multiple applications which require
them. Hence, once the code for a web service is written it should have the ability work with
various application types.
5. Service Autonomy - Services should have control over the logic they encapsulate. The service
knows everything on what functionality it offers and hence should also have complete control over
the code it contains.
6. Service Statelessness - Ideally, services should be stateless. This means that services should not
withhold information from one state to the other. This would need to be done from either the client
application. An example can be an order placed on a shopping site. Now you can have a web
service which gives you the price of a particular item. But if the items are added to a shopping
cart and the web page navigates to the page where you do the payment, the responsibility of the
price of the item to be transferred to the payment page should not be done by the web service.
Instead, it needs to be done by the web application.
7. Service Discoverability - Services can be discovered (usually in a service registry). We have
already seen this in the concept of the UDDI, which performs a registry which can hold
information about the web service.

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.

SOAP Building blocks


The SOAP specification defines something known as a "SOAP message" which is what is sent to the web
service and the client application.

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.

A simple example of a complex type is shown below.

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:element name="Tutorial Name" type="string"/>

<xsd:element name="Tutorial Description" type="string"/>

</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>

<TutorialDescription>All about web services</TutorialDescription>

</GetTutorialInfo>

</soap:Body>

Elements of a SOAP message


One thing to note is that SOAP messages are normally auto-generated by the web service when it is
called.

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 –

 The Envelope element


 The header element and
 The body element.

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.

Restful web services

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.

The key elements of a RESTful implementation are as follows:

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.

Let's assume that we have a RESTful web service is defined at the


location.http://demo.guru99.com/employee . When the client makes any request to this web service, it
can specify any of the normal HTTP verbs of GET, POST, DELETE and PUT. Below is what would
happen If the respective verbs were sent by the client.

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.

The following actions would have their respective meanings.

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

 POST - To create a resource on the server


 GET - To retrieve a resource from the server
 PUT - To change the state of a resource or to update it
 DELETE - To remove or delete a resource from the server

Comparison between Web services

SOAP vs. REST


Let' have a quick overview of SOAP and REST before we do a deep dive into the key differences
between them.

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.

Below are the main differences between SOAP and REST

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

service can offer.


http://demo.guru99.com/Employee/1

 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 You Should Already Know


Before you continue you should have a basic understanding of the following:
 HTML
 JavaScript
 C++

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.

What is a PHP File?


 PHP files can contain text, HTML, JavaScript code, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have a default file extension of ".php"

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, and close files on the 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

How does PHP work?


The best way to explain how PHP works is by comparing it with standard HTML. Imagine you type the
address of an HTML document (e.g. http://www.mysite.com/page.htm) in the address line of the browser.
This way you request an HTML page. It could be illustrated like this:

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

Install Wamp server or XAMPP on your PC to quickly create web


applications with Apache, PHP and a MySQL database.

What Do I Need for PHP Installation?


PHP is a server-side technology. Therefore, you need to have a server to run PHP. But it doesn't need to
cost you anything to make this upgrade and there are several options for doing so.
Since you ultimately only need to choose one option, this lesson is divided into three parts. First comes a
little introduction on the different options (just choose the one that suits you best). When your server is up
and running, we'll pick up with Lesson 3 to make your first PHP page.
To start using PHP, you can:

30
 Find a web host with PHP and MySQL support
 Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host with PHP Support


If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically parse them
for you.
You do not need to compile anything or install any extra tools. Because PHP is free, most web hosts offer
PHP support.

Install PHP on your computer


It's no walk in the park to install PHP on your computer. This option is only recommend for experienced
computer users, but it can obviously be done. Here are links to download and installation guides:
 Windows Installation Guide http://www.php.net/manual/en/install.windows.php
 Mac Installation Guide http://www.php.net/manual/en/install.macosx.php
 Linux Installation Guide http://www.php.net/manual/en/install.unix.php

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:

 Download and install XAMPP for Windows http://www.apachefriends.org/en/xampp-


windows.html
 Download and install XAMPP for Mac http://www.apachefriends.org/en/xampp-macosx.html
 Download and install XAMPP for Linux http://www.apachefriends.org/en/xampp-linux.html

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:

3. You don't need to choose any "Service Sections":

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:

1. Open the program XAMPP Control Panel


2. Start the Apache server and the MySql server:

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").

4. Insert the following code in the file:

<?php echo "Hello World!"; ?>

5. Save the file in the folder "c:\xampp\htdocs".

6. Open the file in your browser with the address http://localhost/test.php.

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.

Common Xampp problems


1. Apache server won't start

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.

2. I don't know where to save my PHP files


You should always save your files in the "htdocs"-folder. If you have made a standard installation in
Windows (see above) the path is "c:\xampp\htdocs\":

 In Notepad choose "Save as…" under "File" in the top menu.


 Find the "\htdocs\" folder (click on the folder-icon next to the path (see image above), and
type: "C:\xampp\htdocs")
 Choose "All Files" in the "Save as type" box. This is very important – otherwise, you save
it as a text document and not as an PHP file.
 Now save your document as i.e. "page.php" (the ending ".php" indicates that it is an PHP
file).
 You can now open the file in your browser with the address http://localhost/page.php.

PHP Syntax

The PHP script can be embedded within HTML web pages.

The PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax

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
?>

The default file extension for PHP files is ".php".

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>

<h1>My first PHP page</h1>

<?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 simply text ignored by the php engine.

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!";
 ?>

PHP Variables and Constants

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.

What is Variables in PHP

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

These are the following rules for naming a PHP variable:

 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.

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

1. local

2. global

3. static

Global and Local Scope


A variable declared outside a function has a global scope and can only be accessed outside a function.
However, inside a function has a local scope and cannot be accessed outside a function.

<?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.

The global keyword

First, an example use of global:

<?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.

Using static variables

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.

 Constants do not have a dollar sign ($) before them.


 Prior to PHP 5.3, Constants may only be defined using the define() function, not by simple
assignment.
 Constants may be defined and accessed anywhere without regard to variable scoping rules.
 Constants may not be redefined or undefined once they have been set; and
 Constants may only evaluate to scalar values. As of PHP 5.6 it is possible to define array
constant.

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 $.

These are the differences between constants and variables:

 Constants do not have a dollar sign ($) before them;


 Prior to PHP 5.3, Constants may only be defined using the define() function, not by simple
assignment;
 Constants may be defined and accessed anywhere without regard to variable scoping rules;
 Constants may not be redefined or undefined once they have been set; and
 Constants may only evaluate to scalar values. As of PHP 5.6 it is possible to define array
constant using const keywords and as of PHP 7 array constants can also be defined
using define() You may use arrays in constant scalar expressions (for example, const FOO =
array(1,2,3)[0];), but the end result must be a value of allowed type.

40
Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Example #2 Defining Constants using the const keyword

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;

// Works as of PHP 5.6.0


const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;

const ANIMALS = array('dog', 'cat', 'bird');


echo ANIMALS[1]; // outputs "cat"

// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>

PHP Data Types

PHP supports total eight primitive data types: Integer, Floating point
number or Float, String, Booleans, Array, Object, resource and NULL.

Data Types in PHP

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.

Four scalar types:

41
 boolean
 integer
 float (floating-point number, double)
 string

Two compound types:

 array
 object

And finally two special types:

 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.

$foo = True; // assign the value TRUE to $foo

if (TRUE)

print("This will always print<br>");

else

print("This will never print<br>");

Interpreting other types as Booleans:

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.

 Values of type NULL are always false.

 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).

 Don't use double as Booleans.


Each of the following variables has the truth value embedded in its name when it is used in a Boolean
context.

$true_num = 3 + 0.14159;

$true_str = "Tried and true"

$true_array[49] = "An array element";

$false_array = array();

$false_null = NULL;

$false_num = 999 - 999;

$false_str = "";

Integers

An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.

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.

Integer overflow on a 32-bit system

<?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)
?>

Integer overflow on a 64-bit system

<?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.

Note: string can be as large as up to 2GB (2147483647 bytes maximum)

Syntax

A string literal can be specified in four different ways:

 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';

echo 'You can also have embedded newlines in


strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"


echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?


echo 'You deleted C:\\*.*?';

45
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline


echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either


echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special
characters:

Escaped characters

\n linefeed (LF or 0x0A (10) in ASCII)


\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ Backslash
\$ dollar sign
\" double-quote

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');
}
}

$foo = new foo();


$name = 'MyName';

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

/* More complex example, with variables. */


class foo
{
public $foo;
public $bar;

function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}

$foo = new foo();


$name = 'MyName';

echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
EOT;
?>

The above example will output:

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:

 It evaluates to FALSE in a Boolean context.

 It returns FALSE when tested with IsSet() function.

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(

key => value,

key2 => value2,

key3 => value3,

...

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

$colors = array("Red", "Green", "Blue");

var_dump($colors);

echo "<br>";

$color_codes = array(

"Red" => "#ff0000",

"Green" => "#00ff00",

"Blue" => "#0000ff"

);

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

public $str = "Hello World!";

// methods

function show_greeting(){

return $this->str;

// Create object from class

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

// Open a file for reading

$handle = fopen("palin.php", "r");

var_dump($handle);

echo "<br>";

// Connect to MySQL database server with default setting

$link = mysql_connect("localhost", "root", "system");

var_dump($link);

?>

PHP Operators

Operators are used to manipulate or perform operations on variables and


values.

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

The assignment operator = is used to assign values to variables in PHP.


The arithmetic operator + is used to add values together in PHP.
Let’s have a look on all operators one by one.

PHP Arithmetic Operators

Operator Name Description Example Result


x+y Addition Sum of x and y 2+2 4

x–y Subtraction Difference of x and y 5–2 3

x*y Multiplication Product of x and y 5*2 10

x/y Division Quotient of x and y 15 / 5 3

5%2 1
Remainder of x divided
x%y Modulus 10 % 8 2
by y
10 % 2 0

–x Negation Opposite of x –2

a.b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

1. <?php

2. $x = 10;

3. $y = 4;

4. echo($x + $y); // 0utputs: 14

5. echo($x - $y); // 0utputs: 6

6. echo($x * $y); // 0utputs: 40

7. echo($x / $y); // 0utputs: 2.5

8. echo($x % $y); // 0utputs: 2

9. ?>

PHP Assignment Operators


The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
expression on the right. That is, the value of "$x = 5" is 5.

Assignment Same as… Description

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

a .= b a=a.b Concatenate two strings

<?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 Incrementing/Decrementing Operators

Operator Name Description

++ x Pre-increment Increments x by one, then returns x

x ++ Post-increment Returns x, then increments x by one

—x Pre-decrement Decrements x by one, then returns x

x— Post-decrement Returns x, then decrements x by one

 <?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 Comparison Operators


Comparison operators allows you to compare two values:

Operator Name Description Example


x == y Equal True if x is equal to y 5==8 returns false

True if x is equal to y, and they


x === y Identical 5==="5" returns false
are of same type

x != y Not equal True if x is not equal to y 5!=8 returns true

x <> y Not equal True if x is not equal to y 5<>8 returns true

True if x is not equal to y, or


x !== y Not identical 5!=="5" returns true
they are not of same type

x>y Greater than True if x is greater than y 5>8 returns false

x<y Less than True if x is less than y 5<8 returns true

Greater than or True if x is greater than or


x >= y 5>=8 returns false
equal to equal to y

Less than or True if x is less than or equal to


x <= y 5<=8 returns true
equal to y

<?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
?>

PHP Logical Operators

Operator Name Description Example


x=6
y=3
x and y And True if both x and y are true
(x < 10 and y > 1) returns
true

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 Array Operators

Operator Name Description

x+y Union Union of x and y

x == y Equality True if x and y have the same key/value pairs

True if x and y have the same key/value pairs in the same


x === y Identity
order and are of the same type

x != y Inequality True if x is not equal to y

x <> y Inequality True if x is not equal to y

x !== y Non-identity True if x is not identical to y

<?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
?>

PHP String Operators


There are two operators which are specifically designed for strings.

Operator Name Description Example

Concatenation of $str1 and


x.y Concatenation $str1 . $str2
$str2

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. ?>

PHP Control Structures

The various statement types are described in this chapter.

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

PHP Conditional Statements


Very often when you write code, you want to perform different actions for different decisions. You can use
conditional statements in your code to do this.
PHP supports following decision making statements:

 if statement – executes some code only if a specified condition is true


 if…else statement – executes some code if a condition is true and another code if the
condition is false
 if…else if….else statement – selects one of several blocks of code to be executed

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!

The If…Else Statement


Use the if….else statement to execute some code if a condition is true and another code if the condition is
false.

Syntax

if (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

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")

echo "Have a nice weekend!";

else

echo "Have a nice day!";

?>

</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")

echo "Hello!<br />";

echo "Have a nice weekend!";

echo "See you on Monday!";

?>

</body>

</html>

The ElseIf Statement


If you want to execute some code if one of several conditions are true use the elseif statement

Syntax

if (condition)

code to be executed if condition is true;

elseif (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

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")

echo "Have a nice weekend!";

elseif ($d=="Sun")

echo "Have a nice Sunday!";

else

echo "Have a nice day!";

?>

</body>

</html>

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax

61
switch (expression)

case label1:

code to be executed if expression = label1;

break;

case label2:

code to be executed if expression = label2;

break;

default:

code to be executed

if expression is different

from both label1 and label2;

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":

echo "Today is Monday";

break;

case "Tue":

echo "Today is Tuesday";

break;

case "Wed":

echo "Today is Wednesday";

break;

case "Thu":

echo "Today is Thursday";

break;

case "Fri":

echo "Today is Friday";

break;

case "Sat":

echo "Today is Saturday";

63
break;

case "Sun":

echo "Today is Sunday";

break;

default:

echo "Wonder which day is this ?";

?>

</body>

</html>

Alternative syntax for control structures

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.

<?php if ($a == 5): ?>


A is equal to 5
<?php endif; ?>

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:

Mixing syntaxes in the same control block is not supported.

Warning

Any output (including whitespace) between a switch statement and the first case will result in a syntax
error. For example, this is invalid:

<?php switch ($foo): ?>


<?php case 1: ?>
...
<?php endswitch ?>

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:

<?php switch ($foo): ?>


<?php case 1: ?>
...
<?php endswitch ?>
//example
<?php
switch ($i):
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
endswitch;
?>

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.

In PHP, we have the following looping statements:

 while – loops through a block of code while a specified condition is true


 do…while – loops through a block of code once, and then repeats the loop as long as a
specified condition is true
 for – loops through a block of code a specified number of times
 foreach – loops through a block of code for each element in an array

The while Loop


The while loop executes a block of code while a condition is true. If the test expression is true then the code
block will be executed. After the code has executed the test expression will again be evaluated and the
loop will continue until the test expression is found to be false.
Syntax:
While group multiple statements within the same while loop by surrounding a group of statements with curly
braces, or by using the alternate syntax:

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;
?>

The do…while Statement


The do…while statement will always execute the block of code once, it will then check the condition, and
repeat the loop while the condition is true.
Syntax

do
{
code to be executed;
}
while (condition);

The example below first sets a variable i to 1 ($i=1;).


Then, it starts the do…while loop. The loop will increment the variable i with 1, and then write some output.
Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run as long as i is
less than, or equal to 5:

<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

The for Loop


The for loop is used when you know in advance how many times the script should run.
Syntax

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 */

for ($i = 1; $i <= 10; $i++) {


echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {


if ($i > 10) {
break;
}
echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);


?>

68
PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):

statement

...

endfor;

The foreach Loop


The foreach loop is used to loop through arrays.
Syntax

foreach (array_expression as $value)

statement

foreach (array_expression as $key => $value)

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

$array1 = array (100, 1100, 200, 400, 900 );


$x1 = 0;
$sum = 0;
while($x1 <= 4)
{
if ($sum > 1500)
{
break; /* You could also write 'break 1;' here. */
}
$sum = $sum + $array1[$x1];
$x1 = $x1 + 1;
}
echo $sum;
?>

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

PHP Include Files


You can include the content of a PHP file into another PHP file before the server executes it. The include
and require statements are used to insert useful codes written in other files, in the flow of execution. There
are two PHP functions which can be used to include one PHP file into another PHP file.

 The include() Function


 The require() Function

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:

include("path/to/filename"); -Or- include "path/to/filename";


require("path/to/filename"); -Or- require "path/to/filename";

The include() Function

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>

Assume we have an include file with some variables defined ("vars.php"):

<?php
$color='red';
$car='BMW';
?>

Then the variables can be used in the calling file:

<html>
<body>

<h1>Welcome to my home page.</h1>


<?php include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>

</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>

This will produce following result:

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!

The require() Function


The require() function takes all the text in a specified file and copies it into the file that uses the include
function. If there is any problem in loading a file then the require() function generates a fatal error and halt
the execution of the script.

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>

This will produce following result

This is an example to show how to include wrong PHP file!

Now lets try same example with require() function.

<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>

This time file execution halts and nothing is displayed.

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';
?>

The above example will output:


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';
?>

The above example will output:

j hit 17

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
loop:
}
}
echo "$i = $i";
?>

The above example will output:

Fatal error: 'goto' into loop or switch statement is disallowed in

script on line 2

74
PHP Functions

A function is a self-contained block of code that performs a specific task.

Table of Contents

 Internal (built-in) functions


 User-defined functions
 Function arguments
 Returning values
 Variable functions
 Anonymous functions

Internal (Built-in) Functions

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.

There are two parts which should be clear to you:

 Creating a PHP Function

 Calling a PHP Function

75
Create a PHP Function
A function will be executed by a call to the function.
Syntax

function functionName()
{
code to be executed;
}

PHP function guidelines:


 Give the function a name that reflects what the function does
 The function name can start with a letter or underscore (not a number)

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:

My name is Kai Jim Refsnes

Example #2 Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here


since it doesn't exist yet,
but we can call bar() */

bar();

if ($makefoo) {

76
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}

/* Now we can safely call foo()


since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
echo "I exist immediately upon program start.\n";
}

?>

Example #3 Functions within functions

<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}

/* We can't call bar() yet


since it doesn't exist. */

foo();

/* Now we can call bar(),


foo()'s processing has
made it accessible. */

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.

Example #4 Recursive functions

77
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>

Functions with Parameters

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.

function myFunc($oneParameter, $anotherParameter){


// Code to be executed
}

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);
 ?>

The output of the above code will be:


Sum of the two numbers 10 and 20 is : 30
Tip:An argument is a value that you pass to a function, and a parameter is the variable within the function
that receives the argument. However, in common usage these terms are interchangeable i.e. an
argument is a parameter is an argument.

Functions with Optional Parameters and Default Values

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.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

Passing arguments by reference

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:

Example #2 Passing function parameters by reference

<?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.'
?>

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

<?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 cappuccino.

Making a cup of .

Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?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:

Example #5 Incorrect usage of default function arguments

80
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry"); // won't work as expected


?>

Output:

Warning: Missing argument 2 in call to makeyogurt() in

/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41

Making a bowl of raspberry .

Now, compare the above with this:

Example #6 Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry"); // works as expected


?>

The above example will output:

Making a bowl of acidophilus raspberry.

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.

Note:If the return is omitted the value NULL will be returned.

Example #1 Use of return

<?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.

Example #2 Returning an array to get multiple values

<?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.

Variable functions won't work with language constructs such


as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make
use of any of these constructs as variable functions.

Example #1 Variable function example

<?php
function foo() {
echo "In foo()<br />\n";
}

function bar($arg = '')


{
echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo


function echoit($string)
{
echo $string;
}

$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.

Example #2 Variable method example

<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}

function Bar()
{
echo "This is Bar";
}
}

$foo = new Foo();


$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()

?>

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);
?>

Example #2 Anonymous function variable assignment example

<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

83
PHP Strings

A string variable is used to store and manipulate a piece of text.

What is String in PHP

A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all.

Manipulating PHP Strings

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.

Calculating the Length of a String

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

2. $my_str = 'Welcome to Tutorial Republic';

3.

4. // Outputs: 28

5. echo strlen($my_str);

6. ?>

Counting Number of Words in a String

The str_word_count() function counts the number of words in a string.

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. ?>

Replacing Text within Strings


The str_replace() replaces all occurrences of the search text within the target string.

<?php

$my_str = 'If the facts do not fit the theory, change the facts.';

// Display replaced string

echo str_replace("facts", "truth", $my_str);

?>

Output:

If the truth do not fit the theory, change the truth.


You can optionally pass the fourth argument to the str_replace() function to know how many times the
string replacements was performed, like this.

1. <?php

2. $my_str = 'If the facts do not fit the theory, change the facts.';

3.

4. // Perform string replacement

5. str_replace("facts", "truth", $my_str, $count);

6.

7. // Display number of replacements performed

8. echo "The text was replaced $count times.";

9. ?>

Output:
The text was replaced 2 times.

Reversing a String
The strrev() function reverses a string.

85
1. <?php

2. $my_str = 'You can do anything, but not everything.';

3.

4. // Display reversed string

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

addcslashes() Returns a string with backslashes before the specified characters

addslashes() Returns a string with backslashes before the characters that need to be
escaped. These characters are single quote ('), double quote ("), backslash (\)
and NULL

bin2hex() Convert binary data into hexadecimal values

chop() Strip whitespace (or other characters) from the end of a string. Alias of rtrim()

chr() Returns a one-character string containing the character specified by ASCII

chunk_split() Split a string into smaller chunks

convert_cyr_string() Converts a string from one Cyrillic character set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Return information about characters used in a string

crc32() Calculates the crc32 polynomial of a string

86
Function Description

crypt() One-way string encryption (or hashing)

echo() Output one or more strings

explode() Split a string into an array by a specified string

fprintf() Write a formatted string to a specified output stream

get_html_translation_table() Returns the translation table used byhtmlspecialchars() and htmlentities()

hebrev() Convert logical Hebrew text to visual text

hebrevc() Convert logical Hebrew text to visual text with newline conversion

hex2bin() Decodes a hexadecimally encoded binary string

html_entity_decode() Convert all HTML entities to their applicable characters

htmlentities() Convert all applicable characters to HTML entities

htmlspecialchars_decode() Convert special HTML entities back to characters

htmlspecialchars() Convert special characters to HTML entities

implode() Return a string by joining the elements of an array with a specified string

join() Alias of implode()

lcfirst() Converts the first character of a string to lowercase

levenshtein() Calculate Levenshtein distance between two strings

localeconv() Returns localized numeric and monetary formatting information

ltrim() Removes whitespace (or other characters) from the beginning of a string

md5() Calculate the md5 hash of a string

md5_file() Calculates the md5 hash of a file

metaphone() Calculate the metaphone key of a string

87
Function Description

money_format() Formats a number as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks before all newlines in a string

number_format() Format a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

parse_str() Parses the string into variables

print() Output a string

printf() Output a formatted string

quoted_printable_decode() Convert a quoted-printable string to an 8 bit string

quoted_printable_encode() Convert a 8 bit string to a quoted-printable string

quotemeta() Quotes meta characters

rtrim() Removes whitespace (or other characters) from the end of a string

setlocale() Set locale information

sha1() Calculate the sha1 hash of a string

sha1_file() Calculate the sha1 hash of a file

similar_text() Calculate the similarity between two strings

soundex() Calculate the soundex key of a string

sprintf() Return a formatted string

sscanf() Parses input from a string according to a format

str_getcsv() Parse a CSV string into an array

str_ireplace() Replace all occurrences of the search string with the replacement string. Case-
insensitive version ofstr_replace().

88
Function Description

str_pad() Pad a string to a certain length with another string

str_repeat() Repeats a string a specified number of times

str_replace() Replace all occurrences of the search string with the replacement string (case-
sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Counts the number of words in a string

strcasecmp() Binary safe comparison of two string (case-insensitive)

strchr() Finds the first occurrence of a string inside another string. Alias of strstr()

strcmp() Binary safe comparison of two string (case sensitive)

strcoll() Locale based comparison of two string (case sensitive)

strcspn() Returns the number of characters found in a string before any part of some
specified characters are found

strip_tags() Strip HTML and PHP tags from a string

stripcslashes() Un-quotes a string quoted with addcslashes()

stripos() Find the position of the first occurrence of a case-insensitive substring in a


string

stripslashes() Un-quotes a quoted string

stristr() Finds the first occurrence of a string inside another string (case-insensitive).
Case-insensitive version of strstr()

strlen() Returns the length of a string

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive)

89
Function Description

strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive)

strncasecmp() Binary safe string comparison of the first n characters (case-insensitive)

strncmp() Binary safe string comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

strpos() Find the position of the first occurrence of a substring in a string

strrchr() Find the last occurrence of a character in a string

strrev() Reverses a string

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)

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase

strtoupper() Converts a string to uppercase

strtr() Translate characters or replace substrings

substr() Return a part of a string

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

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

90
Function Description

trim() Removes whitespace (or other characters) from the beginning and end of a
string

ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to uppercase

vfprintf() Write a formatted string to a specified output stream

vprintf() Output a formatted string

vsprintf() Return a formatted string

wordwrap() Wraps a string to a given number of characters

PHP Arrays

An array can store many values at once within a single variable.

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

Create an Array in PHP


In PHP, the array() function is used to create an array:

array();

PHP Indexed Arrays


These arrays can store numbers, strings and any object but their index will be represented by numbers. By
default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.

<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>

This will produce following result:

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

Get The Length of an Array – The count() Function


The count() function is used to return the length (the number of elements) of an array: Example:

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Output Result:
3

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

<?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>

This will produce following result:

Salary of mohammad is 2000


Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example:

<?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>

This will produce following result:

Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39

PHP Sorting Arrays

The elements of an array can be sorted alphabetically or numerically in


ascending or descending order.

Sort Functions for Arrays


In this chapter, we will go through the following PHP array sort functions:
 sort() – sort arrays in ascending order
 rsort() – sort arrays in descending order
 asort() – sort associative arrays in ascending order, according to the value
 ksort() – sort associative arrays in ascending order, according to the key
 arsort() – sort associative arrays in descending order, according to the value
 krsort() – sort associative arrays in descending order, according to the key

Sort Array in Ascending Order – sort()


The following example sorts the elements of the $cars array in ascending alphabetical order:

<?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

Sort Array in Descending Order – rsort()


The following example sorts the elements of the $cars array in descending alphabetical order:

<?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

Sort Array in Ascending Order, According to Value – asort()


The following example sorts an associative array in ascending order, according to the value:

<?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

Sort Array in Ascending Order, According to Key – ksort()


The following example sorts an associative array in ascending order, according to the key:

<?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

Sort Array in Descending Order, According to Value – arsort()


The following example sorts an associative array in descending order, according to the value:

<?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

Sort Array in Descending Order, According to Key – krsort()


The following example sorts an associative array in descending order, according to the key:

<?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

List of Array Functions with Example

Name Definition Example


The
array_change_key_case() array_change_key_case() <?php
function changes all keys in $age=array("Peter"=>"35","Ben"=>"37","Jo
an array to lowercase or e"=>"43");
uppercase. print_r(array_change_key_case($age,CAS
E_UPPER));
?>

array_chunk() The array_chunk() function <?php


splits an array into chunks of $cars=array("Volvo","BMW","Toyota","Hond
new arrays. a","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>

array_column() The array_column() function <?php


returns the values from a // An array that represents a possible
single column in the input record set returned from a database
array. $a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)
);

$last_names = array_column($a,
'last_name');
print_r($last_names);
?>

array_combine() The array_combine() function <?php


creates an array by using the $fname=array("Peter","Ben","Joe");
$age=array("35","37","43");

99
elements from one "keys"
array and one "values" array. $c=array_combine($fname,$age);
print_r($c);
?>

array_count_values() The array_count_values() <?php


function counts all the values $a=array("A","Cat","Dog","A","Dog");
of an array. print_r(array_count_values($a));
?>
The array_diff() function
array_diff() compares the values of two <?php
(or more) arrays, and returns $a1=array("a"=>"red","b"=>"green","c"=>"bl
the differences. ue","d"=>"yellow");
This function compares the $a2=array("e"=>"red","f"=>"green","g"=>"bl
values of two (or more) ue");
arrays, and return an array
that contains the entries $result=array_diff($a1,$a2);
from array1 that are not print_r($result);
present in array2 or array3, ?>
etc.

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_key() function


array_diff_key() compares the keys of two (or <?php
more) arrays, and returns the $a1=array("a"=>"red","b"=>"green","c"=>"bl
differences. 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_diff_key($a1,$a2);
from array1 that are not print_r($result);
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);
?>

array_fill() The array_fill() function fills <?php


an array with values. $a1=array_fill(3,4,"blue");
print_r($a1);
?>

array_fill_keys() The array_fill_keys() function <?php


fills an array with values, $keys=array("a","b","c","d");
specifying keys. $a1=array_fill_keys($keys,"blue");
print_r($a1);
?>
The array_filter() function
array_filter() filters the values of an array <?php
using a callback function. function test_odd($var)

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. ?>

array_flip() The array_flip() function <?php


flips/exchanges all keys with $a1=array("a"=>"red","b"=>"green","c"=>"bl
their associated values in an ue","d"=>"yellow");
array. $result=array_flip($a1);
print_r($result);
?>
The array_intersect() function
array_intersect() compares the values of two <?php
(or more) arrays, and returns $a1=array("a"=>"red","b"=>"green","c"=>"bl
the matches. ue","d"=>"yellow");
This function compares the $a2=array("e"=>"red","f"=>"green","g"=>"bl
values of two or more arrays, ue");
and return an array that
contains the entries $result=array_intersect($a1,$a2);
from array1 that are present print_r($result);
inarray2, array3, etc. ?>

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) }
?>

array_keys() The array_keys() function <?php


returns an array containing $a=array("Volvo"=>"XC90","BMW"=>"X5","
the keys. Toyota"=>"Highlander");

103
print_r(array_keys($a));
?>

array_map() The array_map() function <?php


sends each value of an array function myfunction($v)
to a user-made function, and {
returns an array with new return($v*$v);
values, given by the user- }
made function.
$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>

array_merge() The array_merge() function <?php


merges one or more arrays $a1=array("red","green");
into one array. $a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
The array_merge_recursive()
array_merge_recursive() function merges one or more <?php
arrays into one array. $a1=array("a"=>"red","b"=>"green");
The difference between this $a2=array("c"=>"blue","b"=>"yellow");
function and print_r(array_merge_recursive($a1,$a2));
the array_merge()function is ?>
when two or more array
elements have the same key.
Instead of override the keys,
the array_merge_recursive()
function makes the value as
an array.

array_multisort() The array_multisort() function <?php


returns a sorted array. You $a=array("Dog","Cat","Horse","Bear","Zebra
can assign one or more ");
arrays. The function sorts the array_multisort($a);
first array, and the other print_r($a);
arrays follow, then, if two or ?>
more values are the same, it
sorts the next array, and so
on.
The array_pad() function
array_pad() inserts a specified number of <?php
elements, with a specified $a=array("red","green");
value, to an array. print_r(array_pad($a,5,"blue"));
Tip: If you assign a negative ?>
size parameter, the function
will insert new elements
BEFORE the original
elements (See example
below).

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);
?>

array_product() The array_product() function <?php


calculates and returns the $a=array(5,5);
product of an array. echo(array_product($a));
?>
The array_push() function
array_push() inserts one or more elements <?php
to the end of an array. $a=array("red","green");
Tip: You can add one value, array_push($a,"blue","yellow");
or as many as you like. print_r($a);
Note: Even if your array has ?>
string keys, your added
elements will always have
numeric keys (See example
below).

array_rand() The array_rand() function <?php


returns a random key from an $a=array("red","green","blue","yellow","bro
array, or it returns an array of wn");
random keys if you specify $random_keys=array_rand($a,3);
that the function should return echo $a[$random_keys[0]]."<br>";
more than one key. echo $a[$random_keys[1]]."<br>";
echo $a[$random_keys[2]];
?>
The array_reduce() function
array_reduce() sends the values in an array <?php
to a user-defined function, function myfunction($v1,$v2)
and returns a string. {
Note: If the array is empty return $v1 . "-" . $v2;
and initial is not passed, this }
function returns NULL. $a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>
The array_replace() function
array_replace() replaces the values of the first <?php
array with the values from $a1=array("red","green");
following arrays. $a2=array("blue","yellow");
Tip: You can assign one array print_r(array_replace($a1,$a2));
to the function, or as many as ?>
you like.

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.

array_reverse() The array_reverse() function <?php


returns an array in the $a=array("a"=>"Volvo","b"=>"BMW","c"=>"
reverse order. Toyota");
print_r(array_reverse($a));
?>

array_search() The array_search() function <?php


search an array for a value $a=array("a"=>"red","b"=>"green","c"=>"blu
and returns the key. e");
echo array_search("red",$a);
?>
The array_shift() function
array_shift() removes the first element <?php
from an array, and returns the $a=array("a"=>"red","b"=>"green","c"=>"blu
value of the removed e");
element. echo array_shift($a);
Note: If the keys are numeric, print_r ($a);
all elements will get new ?>
keys, starting from 0 and
increases by 1 (See example
below).

The array_slice() function


array_slice() returns selected parts of an <?php
array. $a=array("red","green","blue","yellow","bro
wn");

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).

array_splice() The array_splice() function <?php


removes selected elements $a1=array("a"=>"red","b"=>"green","c"=>"bl
from an array and replaces it ue","d"=>"yellow");
with new elements. The $a2=array("a"=>"purple","b"=>"orange");
function also returns an array array_splice($a1,0,2,$a2);
with the removed elements. print_r($a1);
?>

array_sum() The array_sum() function <?php


returns the sum of all the $a=array(5,15,25);
values in the array. echo array_sum($a);
?>
The array_udiff() function
array_udiff() compares the values of two <?php
or more arrays, and returns function myfunction($a,$b)
the differences. {
Note: This function uses a if ($a===$b)
user-defined function to {
compare the values! return 0;
This function compares the }
values of two (or more) return ($a>$b)?1:-1;
arrays, and return an array }
that contains the entries
from array1 that are not $a1=array("a"=>"red","b"=>"green","c"=>"bl
present in array2 or array3, ue");
etc. $a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");

$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.

The array_unshift() function


array_unshift() inserts new elements to an <?php
array. The new array values $a=array("a"=>"red","b"=>"green");
will be inserted in the array_unshift($a,"blue");
beginning of the array. print_r($a);
Tip: You can add one value, ?>
or as many as you like.
Note: Numeric keys will start
at 0 and increase by 1. String
keys will remain the same.

The array_values() function


array_values() returns an array containing all <?php
the values of an array. $a=array("Name"=>"Peter","Age"=>"41","C
Tip: The returned array will ountry"=>"USA");
have numeric keys, starting at print_r(array_values($a));
0 and increase by 1. ?>

array_walk() The array_walk() function <?php


runs each array element in a function myfunction($value,$key)
user-defined function. The {
array's keys and values are echo "The key $key has the value
parameters in the function. $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blu
e");
array_walk($a,"myfunction");
?>

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).

arsort() The arsort() function sorts an <?php


associative array in $age=array("Peter"=>"35","Ben"=>"37","Jo
descending order, according e"=>"43");
to the value. arsort($age);
?>

asort() The asort() function sorts an <?php


associative array in $age=array("Peter"=>"35","Ben"=>"37","Jo
ascending order, according to e"=>"43");
the value. asort($age);
?
The compact() function
compact() creates an array from <?php
variables and their values. $firstname = "Peter";
Note: Any strings that does $lastname = "Griffin";
not match variable names will $age = "41";
be skipped.
$result = compact("firstname", "lastname",
"age");

print_r($result);
?>

count() The count() function returns <?php


the number of elements in an $cars=array("Volvo","BMW","Toyota");
array. echo count($cars);
?>
The current() function returns
current() the value of the current <?php
element in an array. $people = array("Peter", "Joe", "Glenn",
Every array has an internal "Cleveland");
pointer to its "current"
element, which is initialized to echo current($people) . "<br>";
the first element inserted into ?>
the array.
Tip: This function does not
move the arrays internal
pointer.
Related methods:

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

The in_array() function


in_array() searches an array for a <?php
specific value. $people = array("Peter", "Joe", "Glenn",
Note: If the search parameter "Cleveland");
is a string and the type
parameter is set to TRUE, the if (in_array("Glenn", $people))
search is case-sensitive. {
echo "Match found";
}
else
{
echo "Match not found";
}
?>

krsort() The krsort() function sorts an <?php


associative array in $age=array("Peter"=>"35","Ben"=>"37","Jo
descending order, according e"=>"43");
to the key. krsort($age);
?>

ksort() The ksort() function sorts an <?php


associative array in $age=array("Peter"=>"35","Ben"=>"37","Jo
ascending order, according to e"=>"43");
the key. ksort($age);
?>

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.

The rsort() function sorts an


rsort() indexed array in descending <?php
order. $cars=array("Volvo","BMW","Toyota");
Tip: Use the sort() function to rsort($cars);
sort an indexed array in ?>
ascending order.

The sizeof() function returns


sizeof() the number of elements in an <?php
array. $cars=array("Volvo","BMW","Toyota");
The sizeof() function is an echo sizeof($cars);
alias of the count() function. ?>

The sort() function sorts an


sort() indexed array in ascending <?php
order. $cars=array("Volvo","BMW","Toyota");
Tip: Use the rsort() function sort($cars);
to sort an indexed array in ?>
descending order.

The uasort() function sorts an


uasort() array by values using a user- <?php
defined comparison function. function my_sort($a,$b)
Tip: Use the uksort() function {
to sort an array by keys using if ($a==$b) return 0;
a user-defined comparison return ($a<$b)?-1:1;
function. }

$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");
?>

usort() The usort() function sorts an <?php


array using a user-defined function my_sort($a,$b)
comparison function. {
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}

$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). ?>

PHP GET and POST

The HTTP GET and POST methods are used to send information to
server.

Methods of Sending Information to Server


A web browser communicates with the server typically using one of the two HTTP (Hypertext Transfer
Protocol) methods — GET and POST. Both methods pass the information differently and have different
advantages and disadvantages, as described below.

The GET Method

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>

 <title>Example of PHP GET method</title>

 </head>

 <body>

 <?php

 if(isset($_GET["name"])){

 echo "<p>Hi, " . $_GET["name"] . "</p>";

 }

 ?>

 <form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">

 <label for="inputName">Name:</label>

 <input type="text" name="name" id="inputName">

 <input type="submit" value="Submit">

 </form>

 </body>

The POST Method


In POST method the data is sent to the server as a package in a separate communication with the
processing script. Data sent through POST method will not visible in the URL.

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>

 <title>Example of PHP POST method</title>

 </head>

 <body>

 <?php

 if(isset($_POST["name"])){

 echo "<p>Hi, " . $_POST["name"] . "</p>";

 }

 ?>

 <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

 <label for="inputName">Name:</label>

 <input type="text" name="name" id="inputName">

 <input type="submit" value="Submit">

 </form>

 </body>

The $_REQUEST Variable

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>

 <title>Example of PHP $_REQUEST variable</title>

 </head>

 <body>

 <?php

 if(isset($_REQUEST["name"])){

 echo "<p>Hi, " . $_REQUEST["name"] . "</p>";

 }

 ?>

 <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

 <label for="inputName">Name:</label>

 <input type="text" name="name" id="inputName">

 <input type="submit" value="Submit">

 </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

Vous aimerez peut-être aussi