php 1st
php 1st
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 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
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
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.
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.
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.
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.
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.
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:
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.
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 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.
All PHP code goes between the php tag. It starts with <?php and ends with ?>. The
syntax of PHP tag is given below:
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".
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:
<?php
?>
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>
<?php
echo "Hello World!";
?>
</body>
</html>
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>
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
</body>
</html>
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.
// Output "Hello"
echo "Hello";
?>
<?php
//echo “Hello”;
?>
Multi-line Comments:
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
<?php
echo "Hello Geeks";
/* It will print the
message "Hello geeks" */
?>
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>
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>
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-
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.
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.
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>
localhost/posttest.php
Welcome Harry
Your blood group is: O+
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.
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.
<?php
$num1 = 10;
$num2 = 20;
echo $text."\n";
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
?>
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:
echo accepts a list of arguments (multiple arguments print accepts only one
1. can be passed), separated by commas. argument at a time.
It displays the outputs of one or more strings separated The print outputs only the
3. by commas. strings.
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:
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
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:
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
?>
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>";
</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
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;
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
?>
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:
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).
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 _ )
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>
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.
You can assign the same value to multiple variables in one line:
<!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.
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();
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();
</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;
}
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.
<!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++;
}
</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.
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.
Syntax
define(name, value, case-insensitive);
Parameters:
<?php
// case-sensitive constant name
define("GREETING", "Welcome!");
echo GREETING;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
// case-insensitive constant name
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
</body>
</html>
<?php
const MYCAR = "Volvo";
echo MYCAR;
?>
</body>
</html>
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();
</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.
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.
Example:
<?php
$x = 10;
and Logical AND $x and $y True if both the operands are 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
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.
!= 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 or Equal To $x <= $y Returns True if $x is less than or equal to $y
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 .
= Assign $x = $y Operand on the left obtains the value of the operand on the right
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
$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
<?php
$x = array("a" => "one", "b" => "two");
$y = array("c" => "four", "d" => "three");
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
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.
.= 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:
$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)
Example:
<?php
$x = 2;
$y = 3;
$x = 15;
$y = 15;
$x = 10;
$y = 8;
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.
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current
folder.
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.
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) increment/decrement and types right
@
|| logical OR left
?: ternary left
or logical 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.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
$exp = "/abc/i";
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 ~.
PHP provides a variety of functions that allow you to use regular expressions.
Function Description
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
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 description
Example:
<?php
$txt = "W3Schools";
$pattern = "/s/i";
echo preg_match_all($pattern, $txt);
?>
<?php
echo preg_replace($pattern, "#", $txt);
?>
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
?>
<?php
echo preg_replace($pattern, "#", $txt);
?>