PHP BASIC
[Blank Page]
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 IfElse Statement .........................................................................................................58
The ElseIf Statement .............................................................................................................60
The Switch Statement ...........................................................................................................61
Alternative syntax for control structures .................................................................................64
PHP Loops ............................................................................................................................66
The while Loop ......................................................................................................................66
The dowhile 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
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
[Blank Page]
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.
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.
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.
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 diagram below shows a simple example of the communication via SOAP.
10
<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>
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
13
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.
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.
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.
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>
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.
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
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
Access protocol
being
an architectural pattern.
pattern.
REST does not need much bandwidth when requests are sent
25
to a web server. You can see that the size of the message is
comparatively smaller to SOAP.
{"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>
XML, JSON, etc. But the most preferred format for transferring
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!
HTML
JavaScript
C++
What is PHP?
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.
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"
28
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?
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
Option 3: XAMPP
XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHP directly on our
computer without having to install PHP on our own.
Download XAMPP
Start by downloading XAMPP by following these links to download and installation guides:
Install XAMPP
Just follow the instructions on the screen during the installation process. Below are screenshots from an
installation on Windows.
1. Choose the "Installer" download on the XAMPP website:
31
32
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:
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.
34
1.
2.
3.
4.
5.
6.
7.
8.
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.
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
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!";
?>
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
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
$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 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.
This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which
increments the variable serves no purpose since as soon as the function exits the $a variable disappears.
To make a useful counting function which will not lose track of the current count, the $a variable is
declared static:
39
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Now, $a is initialized only in first call of function and every time the test() function is called it will print the
value of $a and increment it.
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script. A constant is case-sensitive by default. By convention, constant
identifiers are always uppercase.
Syntax:
You can define a constant by using the define()-function or by using the const keyword outside a class
definition as of PHP 5.3.0. Once a constant is defined, it can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants prior to PHP 5.6. From
PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to
define an array constant.
You can get the value of a constant by simply specifying its name. Unlike with variables, you
should not prepend a constant with a $.
These are the differences between constants and variables:
40
41
boolean
integer
float (floating-point number, double)
string
array
object
resource
NULL
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the string "0",
and is true otherwise.
If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
42
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
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)
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
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
Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special
characters:
Escaped characters
\n
\r
\t
\v
\e
\f
\\
\$
\"
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
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;
?>
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it
like this:
<?php
$a = NULL;
var_dump($a);
echo "<br>";
?>
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as
well have typed:
A variable that has been assigned NULL has the following properties:
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
Syntax
An array can be created using the array() language construct. It takes any number of commaseparated 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
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>";
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
Assignment Operators
Increment/Decrement Operators
String Operators
51
Array Operators
Name
Description
Example
Result
x+y
Addition
Sum of x and y
2+2
xy
Subtraction
Difference of x and y
52
x*y
Multiplication
Product of x and y
5*2
10
x/y
Division
Quotient of x and y
15 / 5
x%y
Modulus
Remainder of x divided
by y
5%2
10 % 8
10 % 2
1
2
0
Negation
Opposite of x
a.b
Concatenation
"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.
?>
Same as
Description
52
x=y
x=y
x += y
x=x+y
Addition
x -= y
x=xy
Subtraction
x *= y
x=x*y
Multiplication
x /= y
x=x/y
Division
x %= y
x=x%y
Modulus
a .= b
a=a.b
<?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
?>
Operator
Name
Description
++ x
Pre-increment
x ++
Post-increment
Pre-decrement
Post-decrement
<?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
?>
Name
Description
Example
x == y
Equal
True if x is equal to y
x === y
Identical
x != y
Not equal
x <> y
Not equal
x !== y
Not identical
x>y
Greater than
x<y
Less than
x >= y
Greater than or
equal to
x <= y
Less than or
equal to
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
54
Description
Example
And
x=6
y=3
(x < 10 and y > 1) returns
true
Or
x=6
y=3
(x==6 or y==5) returns
true
Xor
x=6
y=3
(x==6 xor y==3) returns
false
And
x=6
y=3
(x < 10 && y > 1) returns
true
x || y
Or
x=6
y=3
(x==5 || y==5) returns
false
!x
Not
x=6
y=3
!(x==y) returns true
x and y
x or y
x xor y
x && y
Name
<?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
?>
Name
Description
x+y
Union
Union of x and y
x == y
Equality
x === y
Identity
x != y
Inequality
x <> y
Inequality
x !== y
Non-identity
<?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
?>
Name
Description
Example
x.y
Concatenation
$str1 . $str2
x .= y
Concatenation
Assignment
$str1 .= $str2
1. <?php
2. $x = "Hello";
3. $y = " World!";
56
4.
5.
6.
7.
8.
if
else
elseif/else if
Alternative syntax for control structures
while
do-while
for
foreach
break
continue
switch
declare
return
require
include
require_once
include_once
goto
57
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!
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>
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>
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>
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:
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;
?>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
67
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;
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
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";
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
Assume you want to create a common menu for your website. Then create a file menu.php with the following
content.
<a href="http://www.mytoptutorials.com/">Home</a>
<a href="http://www.mytoptutorials.com/html/">HTML</a>
<a href="http://www.mytoptutorials.com/php/">PHP</a> <br />
Now create as many pages as you like and include this file to create header. For example now your test.php
file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
72
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>
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
User-defined functions
In addition to the built-in function, PHP also allows you to define your own functions. It is a way to create
reusable code packages that perform specific tasks and can be kept and maintained separately form
main program. Here are some advantages of using functions:
Functions reduces the repetition of code within a program Function allows you to extract
commonly used block of code into a single component. Now can you can perform the same task
by calling this function wherever you want without having to copy and paste the same block of
code again and again.
Functions makes the code much easier to maintain Since a function created once can be
used many times, so any changes made inside a function automatically implemented at all the
places without touching the several files.
Functions makes it easier to eliminate the errors When the program is subdivided into
functions, if any error occur you know exactly what function causing the error and where to find it.
Functions can be reused in other application Because a function is separated from the rest
of the script, it's easy to reuse the same function in other applications just by including the php file
containing those functions.
75
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
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";
}
?>
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);
}
}
?>
<?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);
?>
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.
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];
}
?>
79
echo $str;
?>
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.
1.
<?php
?>
1.
<?php
2. $my_str = 'The quick brown fox jumps over the lazy dog.';
3.
4. // Outputs: 9
5. echo str_word_count($my_str);
84
6.
?>
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
Output:
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()
addslashes()
bin2hex()
chop()
Strip whitespace (or other characters) from the end of a string. Alias of rtrim()
chr()
chunk_split()
convert_cyr_string()
convert_uudecode()
convert_uuencode()
count_chars()
crc32()
86
Function
Description
crypt()
echo()
explode()
fprintf()
hebrevc()
hex2bin()
html_entity_decode()
htmlentities()
htmlspecialchars_decode()
htmlspecialchars()
implode()
join()
Alias of implode()
lcfirst()
levenshtein()
localeconv()
ltrim()
md5()
md5_file()
metaphone()
87
Function
Description
money_format()
nl_langinfo()
nl2br()
number_format()
ord()
parse_str()
print()
Output a string
printf()
quoted_printable_decode()
quoted_printable_encode()
quotemeta()
rtrim()
setlocale()
sha1()
sha1_file()
similar_text()
soundex()
sprintf()
sscanf()
str_getcsv()
str_ireplace()
Replace all occurrences of the search string with the replacement string. Caseinsensitive version ofstr_replace().
88
Function
Description
str_pad()
str_repeat()
str_replace()
Replace all occurrences of the search string with the replacement string (casesensitive)
str_rot13()
str_shuffle()
str_split()
str_word_count()
strcasecmp()
strchr()
Finds the first occurrence of a string inside another string. Alias of strstr()
strcmp()
strcoll()
strcspn()
Returns the number of characters found in a string before any part of some
specified characters are found
strip_tags()
stripcslashes()
stripos()
stripslashes()
stristr()
strlen()
strnatcasecmp()
89
Function
Description
strnatcmp()
strncasecmp()
strncmp()
strpbrk()
strpos()
strrchr()
strrev()
Reverses a string
strripos()
Find the position of the last occurrence of a string inside another string (caseinsensitive)
strrpos()
Find the position of the last occurrence of a string inside another string (casesensitive)
strspn()
strstr()
strtok()
strtolower()
strtoupper()
strtr()
substr()
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()
substr_replace()
90
Function
Description
trim()
Removes whitespace (or other characters) from the beginning and end of a
string
ucfirst()
ucwords()
vfprintf()
vprintf()
vsprintf()
wordwrap()
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
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
Output Result:
3
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>
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>
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
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
97
asort($age);
?>
Output Result:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
98
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
Definition
Example
The
array_change_key_case()
function changes all keys in
an array to lowercase or
uppercase.
<?php
$age=array("Peter"=>"35","Ben"=>"37","Jo
e"=>"43");
print_r(array_change_key_case($age,CAS
E_UPPER));
?>
array_chunk()
<?php
$cars=array("Volvo","BMW","Toyota","Hond
a","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
array_column()
<?php
// An array that represents a possible
record set returned from a database
$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()
99
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
array_count_values()
array_diff()
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
The array_count_values()
function counts all the values
of an array.
The array_diff() function
compares the values of two
(or more) arrays, and returns
the differences.
This function compares the
values of two (or more)
arrays, and return an array
that contains the entries
from array1 that are not
present in array2 or array3,
etc.
The array_diff_assoc()
function compares the keys
and values of two (or more)
arrays, and returns the
differences.
This function compares the
keys and values of two (or
more) arrays, and return an
array that contains the entries
from array1 that are not
present in array2 or array3,
etc.
The array_diff_uassoc()
function compares the keys
and values of two (or more)
arrays, and returns the
differences.
100
$c=array_combine($fname,$age);
print_r($c);
?>
<?php
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"bl
ue");
$result=array_diff($a1,$a2);
print_r($result);
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$result=array_diff_assoc($a1,$a2);
print_r($result);
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pin
k");
$result=array_diff_key($a1,$a2);
print_r($result);
?>
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("d"=>"red","b"=>"green","e"=>"bl
ue");
$result=array_diff_uassoc($a1,$a2,"myfunc
tion");
print_r($result);
?>
array_diff_ukey()
the keys of two arrays (using a userdefined key comparison function), and
return the differences:
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$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()
<?php
$a1=array_fill(3,4,"blue");
print_r($a1);
?>
array_fill_keys()
<?php
$keys=array("a","b","c","d");
$a1=array_fill_keys($keys,"blue");
print_r($a1);
?>
array_filter()
101
<?php
function test_odd($var)
array_flip()
array_intersect()
array_intersect_assoc()
array_intersect_key()
array_intersect_uassoc()
{
return($var & 1);
}
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
The array_intersect_assoc()
function compares the keys
and values of two (or more)
arrays, and returns the
matches.
This function compares the
keys and values of two or
more arrays, and return an
array that contains the entries
from array1 that are present
in array2, array3, etc.
The array_intersect_key()
function compares the
keys of two (or more) arrays,
and returns the matches.
This function compares the
keys of two or more arrays,
and return an array that
contains the entries
from array1 that are present
inarray2, array3, etc.
The array_intersect_uassoc()
function compares the keys
and values of two (or more)
102
$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"bl
ue");
$result=array_intersect($a1,$a2);
print_r($result);
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$result=array_intersect_assoc($a1,$a2);
print_r($result);
?>
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pin
k");
$result=array_intersect_key($a1,$a2);
print_r($result);
?>
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("d"=>"red","b"=>"green","e"=>"bl
ue");
$result=array_intersect_uassoc($a1,$a2,"m
yfunction");
print_r($result);
?>
array_intersect_ukey()
The array_intersect_ukey()
function compares the
keys of two (or more) arrays,
and returns the matches.
Note: This function uses a
user-defined function to
compare the keys!
This function compares the
keys of two or more arrays,
and return an array that
contains the entries
from array1 that are present
inarray2, array3, etc.
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_intersect_ukey($a1,$a2,"myf
unction");
print_r($result);
?>
array_key_exists()
array_keys()
The array_key_exists()
function checks an array for a
specified key, and returns
true if the key exists and false
if the key does not exist.
Tip: Remember that if you
skip the key when you specify
an array, an integer key is
generated, starting at 0 and
increases by 1 for each value.
(See example 2)
103
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","
Toyota"=>"Highlander");
print_r(array_keys($a));
?>
array_map()
<?php
function myfunction($v)
{
return($v*$v);
}
$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>
array_merge()
array_merge_recursive()
array_multisort()
array_pad()
The array_merge_recursive()
function merges one or more
arrays into one array.
The difference between this
function and
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.
104
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge_recursive($a1,$a2));
?>
<?php
$a=array("Dog","Cat","Horse","Bear","Zebra
");
array_multisort($a);
print_r($a);
?>
<?php
$a=array("red","green");
print_r(array_pad($a,5,"blue"));
?>
array_pop()
array_product()
array_push()
array_rand()
array_reduce()
array_replace()
105
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
<?php
$a=array(5,5);
echo(array_product($a));
?>
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
<?php
$a=array("red","green","blue","yellow","bro
wn");
$random_keys=array_rand($a,3);
echo $a[$random_keys[0]]."<br>";
echo $a[$random_keys[1]]."<br>";
echo $a[$random_keys[2]];
?>
<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
array_replace_recursive()
The
array_replace_recursive()
function replaces the values
of the first array with the
values from following arrays
recursively.
Tip: You can assign one array
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.
<?php
$a1=array("a"=>array("red"),"b"=>array("gr
een","blue"),);
$a2=array("a"=>array("yellow"),"b"=>array("
black"));
print_r(array_replace_recursive($a1,$a2));
?>
array_reverse()
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"
Toyota");
print_r(array_reverse($a));
?>
array_search()
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blu
e");
echo array_search("red",$a);
?>
array_shift()
array_slice()
106
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blu
e");
echo array_shift($a);
print_r ($a);
?>
<?php
$a=array("red","green","blue","yellow","bro
wn");
print_r(array_slice($a,2));
?>
array_splice()
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
array_sum()
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
array_udiff()
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_udiff($a1,$a2,"myfunction");
print_r($result);
?>
array_udiff()
107
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","b"=>"blue","c"=>"gre
en");
$result=array_udiff_assoc($a1,$a2,"myfunc
tion");
print_r($result);
?>
array_udiff()
array_udiff_uassoc()
The array_udiff_uassoc()
function compares the keys
and values of two or more
arrays, and returns the
differences.
Note: This function
uses two user-defined
functions for comparison; the
key is used in the first
function and the value is used
in the second!
This function compares the
keys and values of two (or
more) arrays, and return an
array that contains the entries
from array1that are not
present
in array2 or array3, etc.
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","b"=>"blue","c"=>"gre
en");
$result=array_udiff_assoc($a1,$a2,"myfunc
tion");
print_r($result);
?>
<?php
function myfunction_key($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
function myfunction_value($a,$b)
{
if ($a===$b)
{
return 0;
}
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);
?>
array_uintersect()
The array_uintersect()
function compares the
108
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"blue","b"=>"black","e"=>"b
lue");
$result=array_uintersect($a1,$a2,"myfuncti
on");
print_r($result);
?>
array_uintersect_assoc()
array_uintersect_uassoc()
The array_uintersect_assoc()
function compares the keys
and values of two or more
arrays, and returns the
matches.
Note: This function uses a
built-in function to compare
the keys, and a user-defined
function to compare the
values!
This function compares the
keys and values of two (or
more) arrays, and return an
array that contains the entries
from array1that are present
in array2, array3, etc.
The
array_uintersect_uassoc()
function compares the keys
and values of two or more
arrays, and returns the
matches.
Note: This function
uses two user-defined
functions for comparison; the
key is used in the first
function and the value is used
in the second!
This function compares the
keys and values of two (or
more) arrays, and return an
array that contains the entries
from array1that are present
in array2, array3, etc.
109
<?php
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"bl
ue");
$a2=array("a"=>"red","b"=>"blue","c"=>"gre
en");
$result=array_uintersect_assoc($a1,$a2,"m
yfunction");
print_r($result);
?>
<?php
function myfunction_key($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
function myfunction_value($a,$b)
{
if ($a===$b)
{
return 0;
}
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_uintersect_uassoc($a1,$a2,"
myfunction_key","myfunction_value");
print_r($result);
?>
array_unique()
array_unshift()
array_values()
array_walk()
110
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red
");
print_r(array_unique($a));
?>
<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
<?php
$a=array("Name"=>"Peter","Age"=>"41","C
ountry"=>"USA");
print_r(array_values($a));
?>
<?php
function myfunction($value,$key)
{
echo "The key $key has the value
$value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blu
e");
array_walk($a,"myfunction");
?>
array_walk_recursive()
The array_walk_recursive()
function runs each array
element in a user-defined
function. The array's keys and
values are parameters in the
function. The difference
between this function and
thearray_walk() function is
that with this function you can
work with deeper arrays (an
array inside an array).
<?php
function myfunction($value,$key)
{
echo "The key $key has the value
$value<br>";
}
$a1=array("a"=>"red","b"=>"green");
$a2=array($a1,"1"=>"blue","2"=>"yellow");
array_walk_recursive($a2,"myfunction");
?>
arsort()
<?php
$age=array("Peter"=>"35","Ben"=>"37","Jo
e"=>"43");
arsort($age);
?>
asort()
<?php
$age=array("Peter"=>"35","Ben"=>"37","Jo
e"=>"43");
asort($age);
?
compact()
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname",
"age");
print_r($result);
?>
count()
current()
111
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");
echo current($people) . "<br>";
?>
in_array()
<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
krsort()
<?php
$age=array("Peter"=>"35","Ben"=>"37","Jo
e"=>"43");
krsort($age);
?>
ksort()
<?php
$age=array("Peter"=>"35","Ben"=>"37","Jo
e"=>"43");
ksort($age);
?>
112
pos()
rsort()
sizeof()
sort()
uasort()
<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$arr=array("a"=>4,"b"=>2,"c"=>8,d=>"6");
uasort($arr,"my_sort");
?>
uksort()
113
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$arr=array("a"=>4,"b"=>2,"c"=>8,d=>"6");
uksort($arr,"my_sort");
?>
usort()
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
?>
shuffle()
<?php
$my_array =
array("red","green","blue","yellow","purple");
shuffle($my_array);
print_r($my_array);
?>
114
Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the
page with specific query string values.
The GET method is not suitable for passing sensitive information such as the username and
password, because these are fully visible in the URL query string as well as potentially stored in
the client browser's memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL is
limited. So, there is a limitation for the total data to be sent.
PHP provides the superglobal variable $_GET to access all the information sent either through the URL
or submitted through an HTML form using the method="get".
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_GET["name"])){
?>
<label for="inputName">Name:</label>
</form>
</body>
115
It is more secure than GET because user-entered information is never visible in the URL query string
or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as
well as binary data (uploading a file) using POST.
Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark
the page with specific query.
Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via
post method or submitted through an HTML form using the method="post".
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_POST["name"])){
?>
<label for="inputName">Name:</label>
</form>
</body>
116
Example
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
if(isset($_REQUEST["name"])){
?>
<label for="inputName">Name:</label>
</form>
</body>
You will learn more about PHP cookies and form handling in advanced section
Note: The superglobal variables $_GET, $_POST and $_REQUEST are built-in variables that are always
available in all scopes throughout a script.
117