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

php 1st

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports various databases, is platform-independent, and allows for easy embedding within HTML. The document also covers PHP's history, features, installation, and basic syntax for running PHP code using XAMPP.

Uploaded by

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

php 1st

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports various databases, is platform-independent, and allows for easy embedding within HTML. The document also covers PHP's history, features, installation, and basic syntax for running PHP code using XAMPP.

Uploaded by

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

PHP

Introduction to PHP:

PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.3.0 is
the latest version of PHP, which was released on 28 November

 PHP is an acronym for "PHP: Hypertext Preprocessor"


 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server

 PHP is free to download and use. PHP files can contain text, HTML, CSS, JavaScript,
and PHP code
 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php".
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is easy to learn and runs efficiently on the server side. PHP can handle the forms,
such as - collect the data from users using forms, save it into the database, and return
useful information to the user. For example - Registration form.

PHP History:
PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by
Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway
Interface (CGI) binaries written in the C programming language. Originally used for tracking
visits to his online resume, he named the suite of scripts "Personal Home Page Tools," more
frequently referenced as "PHP Tools." Over time, more functionality was desired, and Rasmus
rewrote PHP Tools, producing a much larger and richer implementation. This new model was
capable of database interaction and more, providing a framework upon which users could
develop simple dynamic web applications such as guestbooks. In June of 1995,
Rasmus » released the source code for PHP Tools to the public, which allowed developers to use
it as they saw fit. This also permitted - and encouraged - users to provide fixes for bugs in the
code, and to generally improve upon it.

In September of that year, Rasmus expanded upon PHP and - for a short time - actually dropped
the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 1


PHP
implementation included some of the basic functionality of PHP as we know it today. It had Perl-
like variables, automatic interpretation of form variables, and HTML embedded syntax. The
syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat
inconsistent. In fact, to embed the code into an HTML file, developers had to use HTML
comments. Though this method was not entirely well-received, FI continued to enjoy growth and
acceptance as a CGI tool --- but still not quite as a language. However, this began to change the
following month; in October, 1995, Rasmus released a complete rewrite of the code. Bringing
back the PHP name, it was now (briefly) named "Personal Home Page Construction Kit," and
was the first release to boast what was, at the time, considered an advanced scripting interface.
The language was deliberately designed to resemble C in structure, making it an easy adoption
for developers familiar with C, Perl, and similar languages. Having been thus far limited to
UNIX and POSIX-compliant systems, the potential for a Windows NT implementation was
being explored.

The code got another complete makeover, and in April of 1996, combining the names of past
releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly
evolve PHP from a suite of tools into a programming language in its own right. It included built-
in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support,
and much more. That June, PHP/FI was given a version 2.0 status. An interesting fact about this,
however, is that there was only one single full version of PHP 2.0. When it finally graduated
from beta status in November, 1997, the underlying parsing engine was already being entirely
rewritten.

Though it lived a short development life, it continued to enjoy a growing popularity in still-
young world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users
around the world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains
reported having headers containing "PHP", indicating that the host server did indeed have it
installed. This number equated to approximately 1% of all domains on the Internet at the time.
Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while
there were several minor contributors, it was still primarily developed by an individual.

PHP 3

PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding PHP/FI 2.0
still inefficient and lacking features they needed to power an eCommerce application they were
developing for a university project, Andi Gutmans and Zeev Suraski of Tel Aviv, Israel, began
yet another complete rewrite of the underlying parser in 1997. Approaching Rasmus online, they
discussed various aspects of the current implementation and their redevelopment of PHP. In an
effort to improve the engine and start building upon PHP/FI's existing user base, Andi, Rasmus,
and Zeev decided to collaborate in the development of a new, independent programming
language. This entirely new language was released under a new name, that removed the
implication of limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP',
with the meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to
providing end users with a mature interface for multiple databases, protocols, and APIs, the ease

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 2


PHP
of extending the language itself attracted dozens of developers who submitted a variety of
modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features
introduced in PHP 3.0 included object-oriented programming support and a far more powerful
and consistent language syntax.

In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was
announced by the new PHP Development Team as the official successor to PHP/FI 2.0. Active
development of PHP/FI 2.0, which had all-but ceased as of November of the previous year, was
now officially ended. After roughly nine months of open public testing, when the announcement
of the official release of PHP 3.0 came, it was already installed on over 70,000 domains around
the world, and was no longer limited to POSIX-compliant operating systems. A relatively small
share of the domains reporting PHP as installed were hosted on servers running Windows 95, 98,
and NT, and Macintosh. At its peak, PHP 3.0 was installed on approximately 10% of the web
servers on the Internet.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev
Suraski had begun working on a rewrite of PHP's core. The design goals were to improve
performance of complex applications, and improve the modularity of PHP's code base. Such
applications were made possible by PHP 3.0's new features and support for a wide variety of
third party databases and APIs, but PHP 3.0 was not designed to handle such complex
applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met
these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this
engine, and coupled with a wide range of additional new features, was officially released in May
2000, almost two years after its predecessor. In addition to the highly improved performance of
this version, PHP 4.0 included other key features such as support for many more web servers,
HTTP sessions, output buffering, more secure ways of handling user input and several new
language constructs.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly
driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new
features.

PHP's development team includes dozens of developers, as well as dozens others working on
PHP-related and supporting projects, such as PEAR, PECL, and documentation, and an
underlying network infrastructure of well over one-hundred individual web servers on six of the
seven continents of the world. Though only an estimate based upon statistics from previous
years, it is safe to presume PHP is now installed on tens or even perhaps hundreds of millions of
domains around the world.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 3


PHP
PHP Features:

Performance:

PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and
better performance.

Open Source:

PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its
components are free to download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on its value.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 4


PHP
Web servers Support:

PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.

Security:

PHP is a secure language to develop the website. It consists of multiple layers of security
to prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP can do the
same work in a few lines of code. It has maximum control over the websites like you can
make changes easily whenever you want.

Installation and Configuration of php:

To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack.
It is available for all operating systems. There are many AMP options available in the
market that are given below:

o WAMP for Windows


o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go
for WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

How to install XAMPP server on windows


We will learn how to install the XAMPP server on windows platform step by step. Follow
the below steps and install the XAMPP server on your system.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 5


PHP
Step 1: Click on the above link provided to download the XAMPP server according to
your window requirement.

Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to
make changes in your system. A window will pop-up, where you have to click on
the Next button.

Step 3: Here, select the components, which you want to install and click Next.

Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.

Step 5: Click Next and move ahead.

Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.

Step 7: A finish window will display after successful installation. Click on the Finish button.

Step 8: XAMPP is ready to use. Start the Apache server and MySQL and run the php
program on the localhost.

How to run PHP code in XAMPP


Generally, a PHP file contains HTML tags and some PHP scripting code. It is very easy to
create a simple PHP example. To do so, create a file and write HTML tags + PHP code
and save this file with .php extension.

All PHP code goes between the php tag. It starts with <?php and ends with ?>. The
syntax of PHP tag is given below:

How to run PHP programs in XAMPP


How to run PHP programs in XAMPP PHP is a popular backend programming language.
PHP programs can be written on any editor, such as - Notepad, Notepad++,
Dreamweaver, etc. These programs save with .php extension, i.e., filename.php inside
the htdocs folder.

For example - p1.php.

As I'm using window, and my XAMPP server is installed in D drive. So, the path for the
htdocs directory will be "D:\xampp\htdocs".

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 6


PHP
PHP program runs on a web browser such as - Chrome, Internet Explorer, Firefox, etc.
Below some steps are given to run the PHP programs.

Step 1: Create a simple PHP program like hello world.

1. <?php
2. echo "Hello World!";
3. ?>

Step 2: Save the file with hello.php name in the htdocs folder, which resides inside the
xampp folder.

Step 3: Run the XAMPP server and start the Apache and MySQL.

Step 4: Now, open the web browser and type localhost http://localhost/hello.php on
your browser window.

Step 5: The output for the above hello.php program will be shown.

 PHP Version

To check your php version you can use the phpversion() function:

echo phpversion();

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

 PHP Syntax:

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php

// PHP code goes here

?>

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

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 7


PHP
A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

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

</body>
</html>

 PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.

<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hi PHP!<br>";
echo "Hi PHP!<br>";
EcHo "Hi PHP!<br>";
?>

</body>
</html>

All variable names are case-sensitive!

Example:
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 8


PHP
echo "colour " . $color . "<br>";
echo "My pen " . $COLOR . "<br>";
?>

</body>
</html>

 Embedding PHP Code In Web Pages:


PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal
Home Page.

Example:

First open the file in any editor and then write HTML code according to
requirement. If we have to add PHP code then we can add by simply
adding <?php ….. ?> tags in between and add your PHP code accordingly.

<! DOCTYPE html>


<html>
<head>
<title>PHP</title>
</head>
<body>
<h1>
<?php
echo "hii PHP "
?>
</h1>
</body>
</html>

What is whitespace in HTML?


 HTML generally converts the sequence of all white spaces to a single space. This
means that if you enter a single or a dozen of whitespace characters (space, new line
character or tab) in a row, the only effect in resulting HTML is just a single space.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 9


PHP
Writing Comments:
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose
is to be read by someone who is looking at the code.
Comments can be used to:
 Let others understand your code
 Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code
 Leave out some parts of your code.

 Single Line Comments:

 Single line comments start with //.


 Any text between // and the end of the line will be ignored (will not be executed).
 You can also use # for single line comments, but in this tutorial we will use //.
Example:
<?php

// Output "Hello"
echo "Hello";

?>
<?php
//echo “Hello”;
?>

 Comments to Ignore Code:

We can use comments to prevent code lines from being executed:


// echo "Welcome Home!";

 Multi-line Comments:
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

<?php
echo "Hello Geeks";
/* It will print the
message "Hello geeks" */
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 10


PHP
 Multi-line Comments to Ignore Code:

We can use multi-line comments to prevent blocks of code from being executed:

<!DOCTYPE html>
<html>
<body>
<?php
/*
echo "Welcome to my home!";
echo "php";
*/
echo "Hello!";
?>
</body>
</html>

 Comments in the Middle of the Code


The multi-line comment syntax can also be used to prevent execution of parts inside a code-line:
Example:
<!DOCTYPE html>
<html>
<body>
<p>Using comments to ignore parts of a code line:</p>
<?php
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>

 Sending Data to the Web Browser:


If you’re already tired of creating useless scripts that generate blank pages, rest assured that PHP
can do a lot more than, well, nothing. To build dynamic Web sites with PHP, you begin with
knowing how to send data to the Web browser. PHP has a number of built-in functions written
specifically to accomplish this, the most common being echo() and print().

echo 'Hello, world!';


print "It's nice to see you.";

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 11


PHP
As you can see from the above, either single or double quotation marks will work (the distinction
between the two will be made clear by the chapter’s end). Also note that in PHP all statements (a
line of executed code, in layman’s terms) must end with a semicolon.

PHP provides two methods through which a client (browser) can send information to the server.
These methods are given below, and discussed in detail:

1. GET method
2. POST method

Get and Post methods are the HTTP request methods used inside the <form> tag to send form
data to the server.

HTTP protocol enables the communication between the client and the server where a browser
can be the client, and an application running on a computer system that hosts your website can be
the server.

GET method

The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.

The information sent from an HTML form using the GET method is visible to everyone in the
browser's address bar, which means that all the variable names and their values will be displayed
in the URL. Therefore, the get method is not secured to send sensitive information.

The below code will display an HTML form containing two input fields and a submit button. In
this HTML form, we used the method = "get" to submit the form data.

file: test1.html

1. <html>
2. <body>
3.
4. <form action = "gettest.php" method = "GET">
5. Username: <input type = "text" name = "username" /> <br>
6. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
7. <input type = "submit" />
8. </form>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 12


PHP
9.
10. </body>
11. </html>

Create gettest.php file, which will accept the data sent by HTML form.

file: gettest.php

1. <html>
2. <body>
3.
4. Welcome <?php echo $_GET["username"]; ?> </br>
5. Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
6.
7. </body>
8. </html>
9.
10. The output will look like the below output:
11. Welcome Harry
12. Your blood group is: AB-

Advantages of GET method (method = "get")

o You can bookmark the page with the specific query string because the data sent by the
GET method is displayed in URL.
o GET requests can be cached.
o GET requests are always remained in the browser history.

Disadvantages of GET Method

o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed
2048 characters.
o For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 13


PHP
o The GET method cannot be used to send binary data (such as images or word documents)
to the server.

POST method

Similar to the GET method, the POST method is also used to submit the HTML form data. But
the data submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.

Unlike the GET method, it does not have a limit on the amount of information to be sent. The
information sent from an HTML form using the POST method is not visible to anyone.

The below code will display an HTML form containing two input fields and a submit button. In
this HTML form, we used the method = "post" to submit the form data.

file: test2.html

1. <html>
2. <body>
3.
4. <form action = "posttest.php" method = "post">
5. Username: <input type = "text" name = "username" /> <br>
6. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
7. <input type = "submit" />
8. </form>
9.
10. </body>
11. </html>

Now create posttest.php file to accept the data sent by HTML form.

file: posttest.php

1. <html>
2. <body>
3. Welcome <?php echo $_POST["username"]; ?> </br>
4. Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
5. </body>
6. </html>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 14


PHP
When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:

localhost/posttest.php

The output will look like the below output:

Welcome Harry
Your blood group is: O+

Advantages of POST method (method = "post")

o The POST method is useful for sending any sensitive information because the
information sent using the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a
large amount of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the
POST method goes through the HTTP header. By using secure HTTP, you can ensure
that your data is safe.

Disadvantages of POST Method

o POST requests do not cache.


o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.

 PHP echo statement: It is a language construct and never behaves like a function,
hence no parenthesis is required. But the developer can use parenthesis if they want. The
end of the echo statement is identified by the semi-colon (‘;’). It output one or more
strings. We can use ‘echo‘ to output strings, numbers, variables, values, and results of
expressions. Below is some usage of echo statements in PHP:
Displaying Strings: We can simply use the keyword echo followed by the string to be
displayed within quotes. The below example shows how to display strings with PHP.

Displaying Strings as multiple arguments: We can pass multiple string arguments to


the echo statement instead of a single string argument, separating them by comma (‘,’)

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 15


PHP
operator. For example, if we have two strings i.e “Hello” and “World” then we can pass them
as (“Hello”, “World”).

<?php

// Defining the variables

$text = "Hello, World!";

$num1 = 10;

$num2 = 20;

// Echoing the variables

echo $text."\n";

echo $num1."+".$num2."=";

echo $num1 + $num2;

?>
Displaying Variables: Displaying variables with echo statements is also as easy as displaying
normal strings. The below example shows different ways to display variables with the help of a
PHP echo statement.

<?php

print "Hello, world!";

?>
The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n”
is used for a new line and is also known as line-break.

PHP print statement: The PHP print statement is similar to the echo statement and can be
used alternative to echo many times. It is also a language construct, so we may not use
parenthesis i.e print or print().

The main difference between the print and echo statement is that echo does not behave like a
function whereas print behaves like a function. The print statement can have only one
argument at a time and thus can print a single string. Also, the print statement always returns a
value of 1. Like an echo, the print statement can also be used to print strings and variables.
Below are some examples of using print statements in PHP:

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 16


PHP
Displaying String of Text: We can display strings with the print statement in the same way
we did with echo statements. The only difference is we cannot display multiple strings
separated by comma(,) with a single print statement. The below example shows how to display
strings with the help of a PHP print statement.
<?php

// Defining the variables


$text = "Hello, World!";
$num1 = 10;
$num2 = 20;

// Echoing the variables


print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>
S.No. echo statement print statement

echo accepts a list of arguments (multiple arguments print accepts only one
1. can be passed), separated by commas. argument at a time.

2. It returns no value or returns void. It returns the value 1.

It displays the outputs of one or more strings separated The print outputs only the
3. by commas. strings.

 PHP Data Types

Variables can store data of different types, and different data types can do different things.

PHP data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 17


PHP
PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

Getting the Data Type

You can get the data type of any object by using the var_dump() function.

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
var_dump($x);
?>

</body>
</html>
?>
Data Types define the type of data a variable can store. PHP allows eight different types of data
types. All of them are discussed below. There are pre-defined, user-defined, and special data
types.

1. Integer: Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point. They can be
Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 18
PHP
decimal (base 10), octal (base 8), or hexadecimal (base 16). The default base
is decimal (base 10). The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x. Integer means numeric data with a
negative or positive sign. It holds only whole numbers, i.e., numbers without fractional
part or decimal points.

Rules to be followed:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e.,
-2^31 to 2^31.

2. Double: Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form. By default, the variables add a minimum
number of decimal places. The Double data type is the same as a float as floating-point
numbers or real numbers.
<?php

$nm = NULL;
echo $nm; // this will return no output

// return data type


var_dump($nm);

?>
3. String: Hold letters or any alphabets, even numbers are included. These are written within
double quotes during declaration. The strings can also be written within single quotes, but they
will be treated differently while printing variables. To clarify this look at the example below.:
<!DOCTYPE html>
<html>
<body>

<?php
$x = "Hello world!";
$y = 'Hello world!';

var_dump($x);
echo "<br>";

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 19


PHP
var_dump($y);
?>

</body>
</html>

4.Boolean: Boolean data types are used in conditional testing. Hold only two values, either
TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events
return false. NULL type values are also treated as false in Boolean. Apart from NULL, 0 is
also considered false in boolean. If a string is empty then it is also considered false in boolean
data type.

<?php

if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";

?>
5.Array: Array is a compound data type that can store multiple values of the same data type.
Below is an example of an array of integers. It combines a series of data that are related
together.
<?php

$intArray = array( 10, 20 , 30);

echo "First Element: $intArray[0]\n";


echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n\n";

//returns data type and value


var_dump($intArray);
?>

6.Objects:Objects are defined as instances of user-defined classes that can hold both values
and functions and information for data processing specific to the class. This is an advanced
topic and will be discussed in detail in further articles. When the objects are created, they
inherit all the properties and behaviours from the class, having different values for all the
properties.
Objects are explicitly declared and created from the new keyword.
<?php

class gfg {
var $message;

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 20


PHP
function gfg($message) {
$this->message = $message;
}

function msg() {
return "This is an example of " . $this->message . "!";
}
}

// instantiating a object
$newObj = new gfg("Object Data Type");
echo $newObj -> msg();
?>

NULL: These are special types of variables that can hold only one value i.e., NULL. We
follow the convention of writing it in capital form, but it’s case-sensitive. If a variable is
created without a value or no value, it is automatically assigned a value of NULL. It is written
in capital letters.

<?php

$nm = NULL;
echo $nm; // this will return no output

// return data type


var_dump($nm);

?>

Resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources. For example, consider a
database call. This is an external resource. Resource variables hold special handles for files and
database connections.

 PHP Keywords

PHP has a set of keywords that are reserved words which cannot be used as function names,
class names or method names. Prior to PHP 7, these keywords could not be used as class
property names either:

Keywords are: abstract, as, break etc..

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 21


PHP
Variables are "containers" for storing information.

 Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = "John";

echo $x;
echo "<br>";
echo $y;
?>

</body>
</html>

In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".

When you assign a text value to a variable, put quotes around the value.

Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.

 PHP Variables

A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).

Rules for PHP variables:

 A variable starts with the $ 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 can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 22


PHP
 Variable names are case-sensitive ($age and $AGE are two different variables)

The PHP echo statement is often used to output data to the screen.

 The following example will show how to output text and a variable:

<!DOCTYPE html>
<html>
<body>

<?php
$txt = "php";
echo "I Love $txt!";
?>

</body>
</html>

 Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:

<!DOCTYPE html>
<html>
<body>

<?php
$x = "John";
echo $x;
?>
</body>
</html>
String variables can be declared either by using double or single quotes, but you should be aware
of the differences.

 Assign Multiple Values

You can assign the same value to multiple variables in one line:

All three variables get the value "Fruit"

<!DOCTYPE html>
<html>
Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 23
PHP
<body>

<?php
$x = $y = $z = "Fruit";

echo $x;
echo $y;
echo $z;

?>

</body>
</html>
 PHP Variables Scope
In PHP, variables can be declared anywhere in the script.

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

PHP has three different variable scopes:


 local
 global
 static

 Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>
</body>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 24


PHP
</html>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html>
 PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest(); // run function


echo $y; // output the new value for variable $y
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 25


PHP
</body>
</html>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.

The example above can be rewritten like this:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y;
?>

</body>
</html>
 PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 26


PHP
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>

</body>
</html>

Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.

The variable is still local to the function.

 PHP Constants

Constants are like variables, except that once they are defined they cannot be changed or
undefined.

A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

 Create a PHP Constant

To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive);

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive. Default
is false. Note: Defining case-insensitive constants was deprecated in PHP 7.3. PHP 8.0
accepts only false, the value true will produce a warning.

Create a constant with a case-sensitive name:

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 27


PHP
<!DOCTYPE html>
<html>
<body>

<?php
// case-sensitive constant name
define("GREETING", "Welcome!");
echo GREETING;
?>

</body>
</html>

Create a constant with a case-insensitive name:

<!DOCTYPE html>
<html>
<body>

<?php
// case-insensitive constant name
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>

</body>
</html>

 PHP const Keyword

You can also create a constant by using the const keyword.

Create a constant with the const keyword:


<!DOCTYPE html>
<html>
<body>

<?php
const MYCAR = "Volvo";

echo MYCAR;
?>

</body>
</html>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 28


PHP
const vs. define()

 const are always case-sensitive


 define() has has a case-insensitive option.
 const cannot be created inside another block scope, like inside a function or inside
an if statement.
 define can be created inside another block scope.

 PHP Constant Arrays

From PHP7, you can create an Array constant using the define() function.

<!DOCTYPE html>
<html>
<body>

<?php
define("cars", [
"RolsRoyce",
"BMW",
"Toyota"
]);
echo cars[0];
?>

</body>
</html>
 Constants are Global

Constants are automatically global and can be used across the entire script.

This example uses a constant inside a function, even if it is defined outside the function:

<!DOCTYPE html>
<html>
<body>

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}

myTest();

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 29


PHP
?>

</body>
</html>
 PHP Predefined Constants

PHP has nine predefined constants that change value depending on where they are used, and
therefor they are called "magic constants".

These magic constants are written with a double underscore at the start and the end, except for
the ClassName::class constant.

(Refer Class notes).

PHP Operators:

 Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax
and operations in PHP.

Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Example:

<?php
$x = 10;

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 30


PHP
$y = 3;
echo $x ** $y;
?>

 Logical or Relational Operators:


These are basically used to operate with conditional statements and expressions. Conditional
statements are based on conditions. Also, a condition can either be met or cannot be met so the
result of a conditional statement can either be true or false. Here are the logical operators along
with their syntax and operations in PHP.

Operator Name Syntax Operation

and Logical AND $x and $y True if both the operands are true else false

or Logical OR $x or $y True if either of the operands is true else false

xor Logical XOR $x xor $y True if either of the operands is true and false if both are true

&& Logical AND $x && $y True if both the operands are true else false

|| Logical OR $x || $y True if either of the operands is true else false

! Logical NOT !$x True if $x is false

Example:
<?php
$x = 10;
$x %= 4;

echo $x;
?>

 Comparison Operators:
These operators are used to compare two elements and outputs the result in boolean form. Here
are the comparison operators along with their syntax and operations in PHP.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 31


PHP
Operator Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal

!= Not Equal To $x != $y Returns True if both the operands are not equal

<> Not Equal To $x <> $y Returns True if both the operands are unequal

$x ===
=== Identical Returns True if both the operands are equal and are of the same type
$y

Returns True if both the operands are unequal and are of different
!== Not Identical $x == $y
types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

<= Less Than or Equal To $x <= $y Returns True if $x is less than or equal to $y

Greater Than or Equal


>= $x >= $y Returns True if $x is greater than or equal to $y
To

Example:
<?php
$x = 50;
$y = "100";

var_dump($x === $y); // returns false because types are not equal
?>
2.
<?php
$x = 100;
$y = "pavithra";
var_dump($x <> $y); // returns true because values are not equal
?>

 Assignment Operators:
These operators are used to assign values to different variables, with or without mid-
operations. Here are the assignment operators along with their syntax and operations, that PHP
provides for the operations .

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 32


PHP
Operator Name Syntax Operation

= Assign $x = $y Operand on the left obtains the value of the operand on the right

+= Add then Assign $x += $y Simple Addition same as $x = $x + $y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y

*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y

/= Divide then Assign (quotient) $x /= $y Simple division same as $x = $x / $y

%= Divide then Assign (remainder) $x %= $y Simple division same as $x = $x % $y

 Array Operators:
These operators are used in the case of arrays. Here are the array operators along with their
syntax and operations, that PHP provides for the array operation.
Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

== Equality $x == $y Returns true if both has same key-value pair

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in the same order and of the same
=== Identity
$y type

Non-
!== $x !== $y Returns True if both are not identical to each other
Identity

<> Inequality $x <> $y Returns True if both are unequal

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 33


PHP
Example:Union

<?php
$x = array("a" => "one", "b" => "two");
$y = array("c" => "four", "d" => "three");

print_r($x + $y); // union of $x and $y


?>

Example: Equality

<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");

var_dump($x == $y);
?>
 Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used to
increment or decrement values.
Operator Name Syntax Operation

++ Pre-Increment ++$x First increments $x by one, then return $x

— Pre-Decrement –$x First decrements $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one

— Post-Decrement $x– First returns $x, then decrement it by one

Example: <?php
$x = 10;
echo ++$x;
?>

 String Operators:
This operator is used for the concatenation of 2 or more strings using the concatenation
operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the
argument on the right side to the argument on the left side.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 34


PHP
Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

.= Concatenation and assignment $x.=$y First concatenates then assigns, same as $x = $x.$y

Example 1:
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>

Example 2:
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>

 Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator
or combined comparison operator is denoted by “<=>“. These operators are used to compare
values but instead of returning the boolean results, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand
is greater, it returns 1. The following table shows how it works in detail:

Operator Syntax Operation

$x < $y $x <=> $y Identical to -1 (right is greater)

$x > $y $x <=> $y Identical to 1 (left is greater)

$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 35


PHP
Operator Syntax Operation

$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)

$x == $y $x <=> $y Identical to 0 (both are equal)

$x != $y $x <=> $y Not Identical to 0

Example:
<?php
$x = 2;
$y = 3;

echo ($x <=> $y); // returns -1 because $x is less than $y


echo "<br>";

$x = 15;
$y = 15;

echo ($x <=> $y); // returns 0 because values are equal


echo "<br>";

$x = 10;
$y = 8;

echo ($x <=> $y); // returns +1 because $x is greater than $y


?>

 Execution Operators

PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.

Operator Name Example Explanation

`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current
folder.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 36


PHP
 Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression,
any error message will be ignored that might be generated by that expression.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

 PHP Operators Precedence

Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) (bool) increment/decrement and types right
@

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

& bitwise AND left

^ bitwise XOR left

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 37


PHP
| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= >>= => assignment right

and logical left

xor logical left

or logical left

, many uses (comma) left

 Regular Expression

A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for.

A regular expression is a string that describes a pattern such as phone numbers, credit card
numbers, and email addresses.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and


optional modifiers.

$exp = "/abc/i";

In the example above, / is the delimiter, w3schools is the pattern that is


being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or
space. The most common delimiter is the forward slash (/), but when your
pattern contains forward slashes it is convenient to choose other delimiters such
as # or ~.

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 38


PHP
 Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions.

The most common functions are:

Function Description

preg_match() Returns 1 if the pattern was found in the string


and 0 if not

preg_match_all() Returns the number of times the pattern was


found in the string, which may also be 0

preg_replace() Returns a new string where matched patterns


have been replaced with another string

 Using preg_match()

The preg_match() function will tell you whether a string contains matches of
a pattern

<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
 Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a
string.

<?php

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 39


PHP
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
 Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another
string.

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
 Regular Expression Modifiers

Modifiers can change how a search is performed.

Modifiers description

1)i--- performs case-insensitive search

Example:
<?php
$txt = "W3Schools";
$pattern = "/s/i";
echo preg_match_all($pattern, $txt);
?>

<p>The matches were found here:</p>

<?php
echo preg_replace($pattern, "#", $txt);
?>

2) m--- performs multiline search

Example:
<?php
$txt = "you are better than\nyou think";
$pattern = "/^you/m";
echo preg_match_all($pattern, $txt);
Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 40
PHP
?>

<p>The matches were found here:</p>

<?php
echo preg_replace($pattern, "#", $txt);
?>

Pavithra V R,Dept Of BCA,USMR College,Shankarghatta Page 41

You might also like