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

Presentation (1)

PHP is an open-source scripting language primarily used for web development, created by Rasmus Lerdorf, and stands for 'PHP: Hypertext Preprocessor'. It supports server-side scripting, database integration, and is known for its simplicity, cross-platform compatibility, and extensive community support. The latest version, PHP 8.2.8, was released on July 4th, 2023, and PHP has evolved through various versions since its inception in 1994.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Presentation (1)

PHP is an open-source scripting language primarily used for web development, created by Rasmus Lerdorf, and stands for 'PHP: Hypertext Preprocessor'. It supports server-side scripting, database integration, and is known for its simplicity, cross-platform compatibility, and extensive community support. The latest version, PHP 8.2.8, was released on July 4th, 2023, and PHP has evolved through various versions since its inception in 1994.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

PHP

What is PHP?

PHP is an open-source general purpose scripting language, widely used for website
development. It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP:
Hypertext Preprocessor.

PHP is the world’s most popular server-side programming language. Its latest version PHP
8.2.8, released on July 4th, 2023.
Why Learn PHP?

PHP one of the most preferred languages for creating interactive websites and web applications.
PHP scripts can be easily embedded into HTML. With PHP, you can build

➢ Web Pages and Web-Based Applications


➢ Content Management Systems, and
➢ Ecommerce Applications etc.

A number of PHP based web frameworks have been developed to speed-up the web application
development. The examples are WordPress, Laravel, Symfony etc.
PHP History

PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially,
PHP was supposed to be an abbreviation for "Personal Home Page", but it now stands for the
recursive initialism "PHP: Hypertext Preprocessor".

Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI)
programs in C, which he used to maintain in his personal homepage. Later on, He extended them
to work with web forms and to communicate with databases. This implementation of PHP was
"Personal Home Page/Forms Interpreter" or PHP/FI.

Today, PHP is the world’s most popular server-side programming language for building web
applications. Over the years, it has gone through successive revisions and versions.
PHP Versions

PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He
called this suite of scripts "Personal Home Page Tools". It can be regarded as PHP version 1.0.

• In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and
Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version
2.0 status.

• PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans
rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface
for multiple databases, protocols and APIs, object-oriented programming support, and
consistent language syntax.
• PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers,
HTTP sessions, output buffering, secure ways of handling user input and several new language
constructs.

• PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new
object model and dozens of other new features.

• PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng).
Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP
7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations
and Anonymous Classes.

• PHP 8.0 was released on 26 November 2020. This is a major version having many significant
improvements from its previous versions. One standout feature is Just-in-time compilation (JIT)
that can provide substantial performance improvements. The latest version of PHP is 8.2.8,
released on July 4th, 2023.
PHP – Installation

XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The
letter X in the acronym indicates that it is a cross-platform software, available for use on Windows,
Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference
in its functionality.

To download the respective installer for your operating system, visit


https://www.apachefriends.org/download.html, and download one of the following −

• Windows − https://sourceforge.net/projects/
• Linux − https://sourceforge.net/projects/
• OS X − https://sourceforge.net/projects/
Features of PHP
PHP is Simple and Easy to Learn
The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for
developers to comprehend, particularly for those who are already familiar with other programming
languages. Web apps can be developed quickly because of its generous pre-defined functions.

PHP is Open Source


PHP is free and open-source, meaning we can download it for free, and anyone can use it, modify
it, and distribute. This encourages a sizable and vibrant developer community that uses forums,
tutorials, and documentation to support and contribute to its development.

PHP is Cross-Platform Compatible


Numerous operating systems including Windows, Linux, macOS, and UNIX; and different
databases like MongoDB, PostgreSQL, MySQL are compatible with PHP.
PHP-based apps can operate on several environments without requiring any modifications due to
this cross-platform inter-operability.
Server-Side Scripting in PHP
PHP is mainly used for server-side scripting, which runs scripts on the web server and then
forwards the HTML they process to the web browser on the client. It helps the developers in Form
Submission and Session Management with users across multiple requests.

PHP Supports Easy Integration with Databases


PHP offers strong database interaction support for various DBMS. It offers numerous built-in
functions to achieve the database connection.
PHP also includes database abstraction layer which integrates the communication between the
application and the database. This makes it simple for developers to design database-driven web
applications.

PHP Provides Extensive Library Support


PHP provides extensive libraries for various functionalities like image processing, encryption, PDF
generation, parsing XML and JSON, handling sessions and cookies, and much more.
Security Features in PHP
PHP provides a plethora of built-in functions for data encryption. Developers can also leverage third-party
applications for security. PHP employs security algorithms like Sha1 and MD5 to encrypt strings. Additionally,
functions like filter_var and strip_tags contribute in maintaining a secure environment for the users. PHP also
supports secure communication protocols like HTTPS.

Efficient Memory and Session Management in PHP


PHP is a reliable language due to its efficient memory management and session management. It avoids
unnecessary memory allocation. PHP code runs in its own memory space which makes it faster compared to
other scripting languages making it more efficient. In PHP, the database connections are also fast.

PHP Has Active Community and Support


Since PHP is an open-source platform, it has a vibrant community of developers who actively contribute to its
development, share knowledge, provide support, and create third-party tools and frameworks. Due to this
active community support, PHP remains up-to-date and developers can easily seek help from other community
members in case they get any errors or exceptions while writing PHP codes.
PHP - Syntax

A ".php" file may contain HTML, CSS and JavaScript code blocks along with the PHP code. Hence,
the PHP parser must differentiate between the PHP code from the other elements. The PHP parser
interpreter processes this block and returns the response to the browser.
Escaping from HTML

The PHP parser ignores everything outside of a pair of opening and closing tags. Thus, a PHP file
can have mixed content. This allows PHP to be embedded in HTML documents −

A little advanced example of escaping using conditions is shown below −


PHP - Hello World
Browse to the "htdocs" directory. Save the following script as "hello.php" in it.
Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the
"Hello World" message in the browser window.
PHP – Comments

A comment in any computer program (such as a PHP program) is a certain explanatory text that
is ignored by the language compiler/interpreter. Its purpose is to help the user understand the
logic used in the program algorithm.

There are two commenting formats in PHP −

➢ Single-line Comments
➢ Multi-line Comments
Single-line Comments
They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for
inserting a single-line comment in a program.

Single-line Comments Using "#" Single-line Comments Using "//"


A line in PHP code starting with the "#" symbol is PHP also supports C style of single-line comments
treated as a single-line comment.
with "//" symbol. A line starting with double
oblique symbol is treated as a comment.
Multi-line Comments

Multi-line comments are generally used to provide


pseudocode algorithms and more detailed
explanations when necessary.

The multiline style of commenting is the same as in


C. One or more lines embedded inside the "/*" and
"*/" symbols are treated as a comment.

Example of Multi-line Comment in PHP

Here is the example of a multi-line comment.


PHP - Variables
A variable in PHP is a named memory location that holds data belonging to one of the data types.

➢ PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.
➢ Variable names in PHP are case-sensitive.
➢ Variable names follow the same rules as other labels in PHP. A valid variable name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores.
➢ As per the naming convention, "$name", "$rate_of_int", "$Age", "$mark1" are examples
of valid variable names in PHP.
➢ Invalid variable names: "name" (not having $ prefix), "$rate of int" (whitespace not allowed),
"$Age#1" (invalid character #), "$11" (name not starting with alphabet).

Variables are assigned with the "=" operator, with the variable on the left hand side and the
expression to be evaluated on the right.
No Need to Specify the Type of a Variable

PHP is a dynamically typed language. There is no need to specify the type of a variable. On the
contrary, the type of a variable is decided by the value assigned to it. The value of a variable is
the value of its most recent assignment.
Take a look at this following example −
Automatic Type Conversion of Variables

PHP does a good job of automatically converting types from one to another when necessary. In
the following code, PHP converts a string variable "y" to "int" to perform addition with another
integer variable and print 30 as the result.
Take a look at this following example −
Variables are Assigned by Value

In PHP, variables are always assigned by value. If an expression is assigned to a variable, the
value of the original expression is copied into it. If the value of any of the variables in the
expression changes after the assignment, it doesn’t have any effect on the assigned value.
Assigning Values to PHP Variables by Reference
You can also use the way to assign values to PHP variables by reference. In this case, the new
variable simply references or becomes an alias for or points to the original variable. Changes to
the new variable affect the original and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable
which is being assigned (the source variable).
Take a look at this following example −
Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
• Local Variables
• Global Variables
• Static Variables
• Function Parameters

Variable Naming
Rules for naming a variable is −
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but you cannot use characters
like + , - , % , ( , ) . & , etc
There is no size limit for variables.
PHP - Echo/Print
In PHP, both echo and print statements are used to render the output either on the browser or
the PHP console. Both of them are not functions but they are language constructs. Hence,
parentheses should not be used with either of them.

The "echo" Statement in PHP


The "print" Statement in PHP Output Multiline Strings Using Print/Echo

The print statement is similar to echo, but it Both echo and print statements can output
outputs an expression. multiline strings spanning over more than one
lines in the editor. Take a look at the following
example −

The output will remain the same if we


replace print with echo.
PHP var_dump() Function
One of the built-in functions in PHP is the var_dump() function. This function displays structured
information such as type
PHP - $ and $$ Variables
We know that PHP uses the convention of prefixing the variable names by the "$" symbol. PHP
also has the provision of declaring dynamic variables by prefixing two dollar symbols ($$) to the
name. A variable variable (or a dynamic variable) can be set and used dynamically.
The declaration of a normal variable is like this −

A dynamic variable takes the value of a normal variable and treats that as the name of the
variable. In the above example, "good" can be used as the name of a variable by using two dollar
signs "$$" −

We now have two variables: "$a" with contents "good" and "$$a"
with contents "morning". As a result, the following echo
statements will produce the same output −
Example 1 Example 2
Take a look at this following example − Let's take a look at another example −
PHP - Constants

A constant in PHP is a name or an identifier for a simple value. A constant value cannot change
during the execution of the PHP script.

• By default, a PHP constant is case-sensitive.


• By convention, constant identifiers are always uppercase.
• A constant name starts with a letter or underscore, followed by any number of letters, numbers,
or underscore.
• There is no need to write a dollar sign ($) before a constant, however one has to use a dollar
sign before a variable.
Examples of Valid and Invalid Constant
Difference between Constants and Variables in PHP
Names in PHP

Here are some examples of valid and


• Constants cannot be defined by simple assignment;
invalid constant names in PHP −
they can only be defined using the define()
function.

• Constants may be defined and accessed anywhere


without regard to variable scoping rules.

• Once the Constants have been set, they may not be


redefined or undefined.
PHP – Data Types
The term "data types" refers to the classification of data in distinct categories. PHP has a total of
eight data types that we use to construct our variables −
➢ Integers − Whole numbers, without a decimal point, like 4195.
➢ Doubles − Floating-point numbers like 3.14159 or 49.1.
➢ Booleans − Have only two possible values, either true or false.
➢ NULL − Special type that only has one value: NULL.
➢ Strings − Sequences of characters, like 'PHP supports string operations.'
➢ Arrays − Named and indexed collections of other values.
➢ Objects − Instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
➢ Resources − Special variables that hold references to resources external to PHP (such as
database connections).

The first five are simple types, and the next two (arrays and objects) are compound types.
The compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
PHP - Type Casting
The term "Type Casting" refers to conversion of one type of data to another. Since PHP is a weakly
typed language, the parser coerces certain data types into others while performing certain
operations. For example, a string having digits is converted to integer if it is one of the operands
involved in the addition operation.
Let's take another example. Here, an
Implicit Type Casting integer variable $a is converted to a string
so that it is concatenated with a string
Here is an example of coercive or implicit type
variable.
casting −
In this case, $b is a
string variable, cast
into an integer to
enable addition. It
will produce the
following output −
Type Casting Operators

To convert an expression of one type to another, you need to put the data type of the latter in
parenthesis before the expression.

Some of the type casting operators in PHP are −

➢ (int) or (integer) casts to an integer


➢ (bool) or (boolean) casts to a boolean
➢ (float) or (double) or (real) casts to a float
➢ (string) casts to a string
➢ (array) casts to an array
➢ (object) casts to an object
Casting to Integer

You can easily convert a float value to an integer. Take a look at the following example −
➢ If the string starts with digits followed by non-numeric characters, only the initial digits are
considered.
➢ If the string starts with non-numeric characters and the digits are in the middle, the csting
operator returns "0".
Casting to Float Type
You can use either the (float) or (double) casting operator to explicitly convert a variable or
expression to a float.
Casting to String Type

By using a casting operator, any expression evaluating to a floating-point or integer may be cast to
a string type. Few examples are given below −
Casting to Bool Type
Any non-zero number, either integer or float, is cast to true with (bool) operator. An expression
evaluating to "0" returns false. A string is always cast to true.
Take a look at the following example −
PHP - Type Juggling
PHP is known as a dynamically typed language. The type of a variable in PHP changes dynamically.
This feature is called "type juggling" in PHP.

Explicit type declaration of a variable is neither needed nor supported in PHP. Hence the type of
PHP variable is decided by the value assigned to it, and not the other way around.

Example 1

You can see the type of "$var"


changes dynamically as per the
value assigned to it. This
feature of PHP is called "type
juggling".
Example 2 Example 3
Type juggling also takes place during calculation If a string starts with digits, trailing non-
of expression. In this example, a string variable numeric characters if any, are ignored while
containing digits is automatically converted to performing the calculation. However, PHP parser
integer for evaluation of addition expression. issues a notice as shown below −
Type Casting vs Type Juggling

Note that "type casting" in PHP is a little different from "type juggling".

➢ In type juggling, PHP automatically converts types from one to another when necessary. For

example, if an integer value is assigned to a variable, it becomes an integer.

➢ On the other hand, type casting takes place when the user explicitly defines the data type in

which they want to cast.


PHP - Strings

A string is a sequence of characters, like 'PHP supports string operations.' A string in PHP as an
array of bytes and an integer indicating the length of the buffer. In PHP, a character is the same
as a byte.

Single-Quoted String Double-Quoted String

A sequence of characters enclosed in


A sequence of characters enclosed in single double-quotes (" ") is another string
quotes (the character ') is a string.
representation.
String Concatenation Operator

To concatenate two string variables together, PHP uses the dot (.) operator −

The strlen() Function


The strlen() function is used to find the length of
a string.
The strpos() Function
The strpos() function is used to search for a string or character within a string.

➢ If a match is found in the string, this function will return the position of the first match.
➢ If no match is found, it will return FALSE.
PHP - Boolean

PHP, "bool" is one of the built-in scalar data types. It is used to express the truth value, and it can
be either True or False. A Boolean literal uses the PHP constants True or False. These constants
are case-insensitive, in the sense, true, TRUE or True are synonymous.

You can declare a variable of bool type as follows −

Example
Logical operators (<, >, ==, !=, etc.) return
Boolean values.
Converting a Value to Boolean

➢ Use the (bool) casting operator to convert a value to bool. When


a value is used in a logical context it will be automatically
interpreted as a value of type bool.

➢ A non-zero number is considered as true, only 0 (+0.0 or -0.0)


is false. Non-empty string represents true, empty string "" is
equivalent to false. Similarly, an empty array returns false.
What are Operators in PHP?
PHP also has operators which are symbols (sometimes keywords) that are predefined to perform
certain commonly required operations on one or more operands.

For example, using the expression "4 + 5" is equal to 9. Here "4" and "5" are called operands and

"+" is called an operator.

We have the following types of operators in PHP −


➢ Arithmetic Operators
➢ Comparison Operators
➢ Logical Operators
➢ Assignment Operators
➢ String Operators
➢ Array Operators
➢ Conditional (or Ternary Operators)
Arithmetic Operators in PHP

Operator Description Example

+ Adds two operands $a + $b = 62

- Subtracts second operand from the first $a - $b = 22

* Multiply both operands $a * $b = 840

/ Divide numerator by de-numerator $a / $b = 2.1

% Modulus Operator and remainder of after an integer division $a % $b = 2

++ Increment operator, increases integer value by one $a ++ = 43

-- Decrement operator, decreases integer value by one $a -- = 42


Comparison Operators in PHP
Operator Description Example

Checks if the value of two operands are equal or not, if yes then condition ($a == $b) is not
==
becomes true. true

Checks if the value of two operands are equal or not, if values are not
!= ($a != $b) is true
equal then condition becomes true.

Checks if the value of left operand is greater than the value of right
> ($a > $b) is false
operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of right operand,
< ($a < $b) is true
if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the value of
>= ($a >= $b) is false
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than or equal to the value of
<= ($a <= $b) is true
right operand, if yes then condition becomes true.
Logical Operators in PHP

Operator Description Example

Called Logical AND operator. If both the operands are true then condition
and (A and B) is true
becomes true.

Called Logical OR Operator. If any of the two operands are non zero then
or (A or B) is true
condition becomes true.

Called Logical AND operator. If both the operands are non zero then
&& (A && B) is true
condition becomes true.

Called Logical OR Operator. If any of the two operands are non zero then
|| (A || B) is true
condition becomes true.

Called Logical NOT Operator. Use to reverses the logical state of its
! !(A && B) is false
operand. If a condition is true then Logical NOT operator will make false.
Assignment Operators in PHP
Operator Description Example

Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand value of A + B into C

Add AND assignment operator, It adds right operand to the left C += A is equivalent to
+=
operand and assign the result to left operand C=C+A

Subtract AND assignment operator, It subtracts right operand from C -= A is equivalent to C


-=
the left operand and assign the result to left operand =C-A

Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C


*=
with the left operand and assign the result to left operand =C*A

Divide AND assignment operator, It divides left operand with the C /= A is equivalent to C
/=
right operand and assign the result to left operand =C/A

Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to


%=
operands and assign the result to left operand C=C%A
String Operators in PHP
There are two operators in PHP for working with string data types −

• The "." (dot) operator is PHP's concatenation operator. It joins two string operands (characters
of right hand string appended to left hand string) and returns a new string.

• PHP also has the ".=" operator which can be termed as the concatenation assignment operator.
It updates the string on its left by appending the characters of right hand operand.
Array Operators in PHP

Symbol Example Name Result

+ $a + $b Union Union of $a and $b.

== $a == $b Equality TRUE if $a and $b have the same key/value pairs.

TRUE if $a and $b have the same key/value pairs in the same


=== $a === $b Identity
order and of the same types.

!= $a != $b Inequality TRUE if $a is not equal to $b.

<> $a <> $b Inequality TRUE if $a is not equal to $b.

!== $a !== $b Non identity TRUE if $a is not identical to $b.


Conditional Operators in PHP
Operator Description Example
?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Operator Precedence in PHP


PHP - Arithmetic Operators Examples
PHP - Comparison Operators Examples
PHP - Logical Operators Examples
PHP - Assignment Operators Examples
PHP – String Operators

Concatenation Operator in PHP Concatenation Assignment Operator in PHP


PHP – Conditional Operators Examples
PHP - Spread Operator
PHP recognizes the three dots symbol (...) as the spread operator. The spread operator is also
sometimes called the splat operator. This operator was first introduced in PHP version 7.4. It
can be effectively used in many cases such as unpacking arrays.

Example 1
In the example below, the elements in $arr1 are inserted in $arr2 after a list of its own elements.
Example 2 Example 3
PHP - Null Coalescing Operator
The Null Coalescing operator is one of the many new features introduced in PHP 7. The word
"coalescing" means uniting many things into one. This operator is used to replace the ternary
operation in conjunction with the isset() function.

Example
Let us use the ternary operator to check if a certain variable is set or not with the help of the
isset() function, which returns true if declared and false if not.
The Null Coalescing Operator is represented by the "??" symbol. It acts as a convenient shortcut
to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null;
otherwise it returns its second operand.
Example - The following code reads the name variable from the URL. If indeed there is a value
for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the
user is called Guest.
PHP – Decision Making

Decision Making Statements in PHP

PHP supports the following three decision making statements −

• if...else statement − Use this statement if you want to execute a set of code when a condition is true

and another if the condition is not true.

• elseif statement − Use this statement with the if...else statement to execute a set of code if one of

the several conditions is true

• switch statement − If you want to select one of many blocks of code to be executed, use the Switch

statement. The switch statement is used to avoid long blocks of if..elseif..else code.
PHP - If…Else Statement
Using endif in PHP
PHP code is usually intermixed with HTML script. We can insert HTML code in the if part as well
as the else part in PHP code. PHP offers an alternative syntax for if and else statements. Change
the opening brace to a colon (:) and the closing brace to endif; so that a HTML block can be
added to the if and else part.Open

Make sure that the above script is in the


document root of PHP server. Visit the
URL http://localhost/hello.php. Following
output should be displayed in the browser, if the
current day is not a Friday −
Using elseif in PHP

Example
Let us modify the above code to display
a different message on Sunday, Friday
and other days.
PHP - Switch Statement
The switch statement in PHP can be treated as an alternative to a series of if…else statements
on the same expression
The switch-endswitch Statement
PHP allows the usage of alternative syntax by delimiting the switch construct
with switch-endswitch statements.
PHP – Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

❑ for − Loops through a block of code a specified number of times.


❑ foreach − Loops through a block of code for each element in an array.
❑ while − Loops through a block of code if and as long as a specified condition is true.
❑ do-while − Loops through a block of code once, and then repeats the loop as long as a
special condition is true.
PHP - For Loop
A program by default follows a sequential execution of statements.

The for statement is used when you know how many times you want to execute a statement or a
block of statements.
Syntax of "for" Loop
The syntax of for statement in PHP is similar to the for statement in C language.

An infinite "for" loop


Using the "for…endfor" construct
You can also use the ":" (colon) symbol to start the
looping block and put endfor statement at the end of the
block.
PHP - Foreach Loop

The foreach loop in PHP can be used with indexed array as well as associative array. There are
two types of usage syntaxes available −

The left side method is useful when you want to


iterate an indexed array. The syntax below is more
suitable for associative arrays.

However, both these approaches work well with


indexed array, because the index of an item in the
array also acts as the key.
PHP - While Loop

The value of the expression is checked each time at the beginning of the loop. If
the while expression evaluates to false from the very beginning, the loop won't even be run once.
Even if the expression becomes false during the execution of the block, the execution will not stop
until the end of the iteration.

The syntax of while loop can be expressed as follows −


Using the "endwhile" Statement PHP - Do…While Loop
This type of loop is similar to the while loop, except that
the test condition is checked at the end of each iteration
rather than at the beginning of a new iteration.
The syntax for constituting a
"do…while" loop is similar to its
counterpart in C language.
Nested "do…while" Loops
PHP - Break Statement PHP - Continue Statement
The break statement inside the The continue statement skips the current
looping block takes the program flow iteration and continues execution at the
outside the block, abandoning the rest condition evaluation and then the beginning
of iterations that may be remaining. of the next iteration.
PHP - Arrays

An array is a data structure that stores one or more data values having some relation among
them, in a single variable. For example, if you want to store the marks of 10 students in a
class, then instead of defining 10 different variables, it’s easy to define an array of 10 length.

There are two ways to declare an array in PHP. One is to use the built-in array() function,
and the other is to use a shorter syntax where the array elements are put inside square
brackets.

The array() Function Using Square Brackets [ ]


Types of Arrays in PHP
There are three different kind of arrays and each array value is accessed using an ID which is
called the array index.

• Indexed Array − An array which is a collection of values only is called an indexed array. Each value
is identified by a positional index staring from "0". Values are stored and accessed in linear
fashion.
• Associative Array − If the array is a collection of key-value pairs, it is called as an associative array.
The key component of the pair can be a number or a string, whereas the value part can be of
any type. Associative arrays store the element values in association with key values rather than
in a strict linear index order.
• Multi Dimensional Array − If each value in either an indexed array or an associative array is an
array itself, it is called a multi dimensional array. Values are accessed using multiple indices
Accessing the Array Elements
To access any element from a given array, you can use the array[key] syntax.
Example
For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.
PHP - Indexed Array

An indexed array in PHP may be created either by using the array() function or with the square
bracket syntax.

Traversing an Indexed Array in PHP


Traversing an Indexed Array Using "foreach" Loop
PHP - Associative Array
If each element in a PHP array is a key-value pair, such an array is called an associative array.
In this type of array, each value is identified by its associated key and not an index.

• Associative arrays are used to implement data structures such as dictionary, maps, trees, etc.
• In PHP, the "=>" symbol is used to establish association between a key and its value.
Accessing the Value with its Key
PHP - Multidimensional Array
A multidimensional array is an array of arrays. In a PHP array, each element can be another array.
Iterating over a 2D Array

Two nested loops will be


needed to traverse all the
elements in a 2D array.
The foreach loop is more
suitable for array traversal. A
2D array is like a tabular
representation of data in rows
and columns.
Here is an example of a three-dimensional array −
PHP - Functions
A function in PHP is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree of
code reuse.

Types of Functions

• Built-in functions − PHP’s standard library contains a large number of built-in functions for
string processing, file IO, mathematical computations and more.

• User-defined functions − You can create user-defined functions too, specific to the
requirements of the programming logic.

A function may be invoked from any other function by passing required data
(called parameters or arguments). The called function returns its result back to the calling
environment.
User-defined Functions in PHP
Suppose you want to create a PHP function which will simply write a simple message on your
browser when you will call it.
There are two parts which should be clear to you −
• Creating a PHP Function
• Calling a PHP Function
PHP - Function Parameters

When a parameterized function needs to be


called, you have to make sure that the
same number of values as in the number of
arguments in function’s definition, are
passed to it.
Formal and Actual Arguments

Sometimes the term argument is used for parameter. Actually, the two terms have a certain
difference.
• A parameter refers to the variable used in function’s definition, whereas an argument refers to
the value passed to the function while calling.
• An argument may be a literal, a variable or an expression
• The parameters in a function definition are also often called as formal arguments, and what is
passed is called actual arguments.
• The names of formal arguments and actual arguments need not be same. The value of the
actual argument is assigned to the corresponding formal argument, from left to right order.
• The number of formal arguments defined in the function and the number of actual arguments
passed should be same.
PHP raises
an ArgumentCountError when the
number of actual arguments is less than
formal arguments. However, the
additional actual arguments are ignored
if they are more than the formal
arguments.
Arguments Type Mismatch
PHP is a dynamically typed
language, hence it doesn’t enforce
type checking when copying the
value of an actual argument with a
formal argument. However, if any
statement inside the function body
tries to perform an operation
specific to a particular data type
which doesn’t support it, PHP
raises an exception.
However, PHP is a weakly typed language. It
attempts to cast the variables into
compatible type as far as possible. Hence, if
one of the values passed is a string
representation of a number and the second
is a numeric variable, then PHP casts the
string variable to numeric in order to
perform the addition operation.
PHP - Call by Value

PHP uses the "call by value" mechanism for passing arguments to a function. When a function

is called, the values of actual arguments are copied to the formal arguments of the function’s

definition.

During the execution of the function body, if there is any change in the value of any of

the formal arguments, it is not reflected in the actual arguments.

• Actual Arguments − The arguments that are passed in a function call.

• Formal Arguments − The arguments that are declared in a function definition.


Example
Let us consider the function used in the code below −
Example
Here is another example of calling a function by passing the argument by value. The function
increments the received number by 1, but that doesn’t affect the variable passed to it.
PHP - Call by Reference

PHP uses the "call by value" mechanism, by default, for passing arguments to a function. If the

arguments within the function are changed, the changes do not reflect outside of the function. To

allow a function to modify its arguments, the "call by reference" mechanism must be used the

following PHP script will help in understanding what references are. Here, $var is a normal string

variable. We declare $var1 as a reference to $var, append "&" symbol to the latter.

When we say that $var1 is an alias or reference of $var, it means any change in its value will
also change the value of $var, and vice versa.
Example
The following example demonstrates how "call by reference" works in PHP −
Calling a PHP Function by Reference
To call a function by reference, you need to declare the formal arguments with name prefixed by
"&" symbol.
Swapping Two Variables
Return by Reference
Just as a function in PHP can accept arguments by reference, it can also return a reference. To
define a function that returns a reference, prefix the name of the function by "&" symbol.
PHP - Default Arguments
a function in PHP may have one or more arguments that have a default value. As a result, such a
function may be called without passing any value to it. If there is no value meant to be passed,
the function will take its default value for processing. If the function call does provide a value, the
default value will be overridden.
Example 2
If you declare arguments with default before arguments without defaults, such function can be
only called if values for both are passed. You cannot have a situation where the first argument
uses the default, and the second using the passed value.
The greeting() function now has $arg1 with default and $arg2 without any default value.
Example 3
Let's define a function percent() that calculates the percentage of marks in three subjects.
Assuming that the marks in each subject are out of 100, the $total argument in the function
definition is given a default value as 300.
However, if the maximum marks in each subject is 50, then you must pass the fourth value to
the function, otherwise the percentage will be calculated out of 300 instead of 150.
PHP - Named Arguments
The feature of Named Arguments has been introduced in PHP with the version 8.0. It is an
extension of the existing mechanism of passing positional arguments to a function while calling.
Passing Named Arguments from an Array
PHP 8.1.0 also introduced another feature that allows using named argument after unpacking
the arguments. Instead of providing values to each argument individually, the values in an array
an be unpacked into the corresponding arguments, using "..." (three dots) before the array.

Note that passing the same parameter multiple


times results in an exception as follows −
PHP - Variable Arguments

it is possible to write a function capable of accepting a list of arguments with variable number of
elements. To declare a variable argument list, the name of the argument is prepended by the "..."
(three dots) symbol. The values passed are collected into an array with the argument’s name.
Try changing the size of the passed array and run the program again.
You can use a foreach loop to traverse the array inside the function. The function may have any
positional arguments before the variable length argument. From the received values, the
positional arguments will be populated first, leaving others to be copied to the array.
Variadic Functions
It is possible to process a variable number of arguments to a function, even without the "..."
syntax. PHP has built_in functions like func_num_args(), func_get_arg() and func_get_args(),
which can be used with similar result.
• func_num_args() − Returns the number of arguments passed to the function.
• func_get_arg() − Returns an item from the argument list
• func_get_args() − Returns an array comprising a function's argument list
PHP - Returning Values

A function is an independent, complete and reusable block of statements. When called, it


performs a certain task and sends the program control back to position from where it was called
even if return statement is not used. The return statement allows it to take a value, along with
the control, back to the calling environment.
Conditional Return
You can have multiple return statements executed under different conditional statements.
Return Multiple Values as Array
The function in PHP is capable of returning only a single value. However, that single value can be
an array of more than one values. We can take the advantage of this feature to return the square
as well as the cube of a number at once.
PHP - Passing Functions
To a function in PHP, in addition to scalar types, arrays, and objects, you can also pass a function as
one of its arguments. If a function is defined to accept another function as an argument, the passed
function will be invoked inside it.

array_map
The array_map() is one of the built-in functions. The first argument to this function is a callback
function. There may be one or more arrays as the other arguments. The callback function is
applied to all the elements of arrays. returns an array.
call_user_func
Another example of passing a function to another function is call_user_func(). As the name
suggests, it calls another user defined callback function, and the other arguments are passed to
the callback.
usort
As another example of passing function, we take a look a usort() function. The first
parameter is an array. The array is sorted as per the callback function, which is the second
parameter.
Pass Callback to User-defined
Function
Apart from the above built-in
functions, you can define your own
function that accepts one of the
arguments as another function.
In the example below, we have two
functions, square() and cube(), that
return the square and cube of a
given number.
PHP - Recursive Functions
A recursive function is such a function that calls itself until a certain condition is satisfied. In PHP,
it is possible to defines a recursive function.
PHP - Variable Scope

In PHP, the scope of a variable is the context within which it is defined and accessible to the
extent in which it is accessible.

Based on the scope, a PHP variable can be any of these three types −
• Local Variables
• Global Variables
• Static Variables
A variable in a main script is also made available to any other script incorporated
with include or require statements.
Example - In the following example, a "test.php" script is included in the main script.
However, when the script has a user defined function, any variable inside has a local scope. As a
result, a variable defined inside a function can't be accessed outside. Variables defined outside
(above) the function have a global scope.

Example
Take a look at the following example −

Note that a global variable is not


automatically available within the local
scope of a function. Also, the variable
inside a function is not accessible
outside.
The "global" Keyword
To enable access to a global variable inside local scope of a function, it should be explicitly done
by using the "global" keyword.
Static Variable
A variable defined with static keyword is not initialized at every call to the function. Moreover, it
retains its value of the previous call.
PHP - Strict Typing

PHP is widely regarded as a weakly typed language. In PHP, you need not declare the type of a
variable before assigning it any value. The PHP parser tries to cast the variables into compatible
type as far as possible.
For example, if one of the values passed is a string representation of a number, and the second is
a numeric variable, PHP casts the string variable to numeric in order to perform the addition
operation.
PHP can be made to impose stricter rules for type conversion, so that "10" is not implicitly
converted to 10. This can be enforced by setting strict_types directive to 1 in a declare() statement.
The declare() statement must be the first statement in the PHP code, just after the "<?php" tag.
PHP - Anonymous Functions
PHP allows defining anonymous functions. Normally, when we define a function in PHP, we usually
provide it a name which is used to call the function whenever required. In contrast, an anonymous
function is a function that doesn’t have any name specified at the time of definition. Such a
function is also called closure or lambda function.

Sometimes, you may want a function for one time use only. The most common use of anonymous
functions is to create an inline callback function.
Anonymous Function as a Callback
Anonymous functions are often used as callbacks. Callback functions are used as one of the
arguments of another function.

Example
In this example, we use an anonymous function
inside the usort() function, a built in function that
sorts an array by values using a user-defined
comparison function.
Anonymous Function as Closure
Closure is also an anonymous function that can access the variables outside its scope with the
help of the "use" keyword.
Example
Take a look a the following example −
PHP - Arrow Functions
Arrow functions provide a simpler and more concise syntax for writing anonymous
functions. A keyword "fn" has been introduced for defining arrow functions, instead of the
conventional use of the "function" keyword.

➢ There is only one expression after the "=>" symbol, and its value is the return value of the arrow
function.
➢ The arrow function doesn’t have an explicit return statement.
➢ Like in the anonymous function, the arrow function is assigned to a variable for it to be called.
Using the Arrow Function as a Callback Function

Example
In this example, we use an arrow function inside usort() function, a built_in function that sorts an
array by values using a user-defined comparison function.
Example
Arrow functions capture variables by value automatically, even when nested.
In the following example, an arrow function is defined in the expression part of another arrow
function.
PHP - Superglobals

The PHP parser populates the current script with a number of predefined variables in its global
namespace. The predefined variables are known as "PHP superglobals".
• Any user defined variable declared outside of any function, method, or class also is a global
variable. However, to access it, you need to use the global keyword.
• In contrast, superglobals are always available anywhere in the PHP script, without mentioning them
with the global keyword.

The list of superglobal variables in PHP includes the following −


• $GLOBALS • $_FILES
• $_SERVER • $_COOKIE
• $_GET • $_SESSION
• $_POST • $_REQUEST
• $_ENV
PHP - $GLOBALS
$GLOBALS is one of the "superglobal" or "automatic global" variables in PHP. It is available in
all scopes throughout a script. There is no need to do "global $variable;" to access it within
functions or methods.
PHP - $_SERVER
$_SERVER is a superglobal in PHP. It holds information regarding HTTP headers, path and script
location, etc.
PHP - $_REQUEST
In PHP, $_REQUEST is a superglobal variable. It is an associative array which is a collection of
contents of $_GET, $_POST and $_COOKIE variables.

$_REQUEST with GET Method


Save the following script in the document folder of the Apache server. If you are using XAMPP
server on Windows, place the script as "hello.php" in the "c:/xampp/htdocs" folder.

Start the XAMPP server and


enter http://localhost/hello.php?first_name=Amar&last_name=Sharma as
the URL in a browser window.
You should get the output as −
$_REQUEST with POST Method
Under the document root, save the following script as "hello.html".
In your browser, enter the URL
"http://localhost/hello.html".
You should get the
similar output in the browser
window.

You may also


embed the PHP
code inside the
HTML script and
POST the form to
itself with the
PHP_SELF
variable −
PHP - $_POST
$_POST is one of the predefined or superglobal variables in PHP. It is an associative array of key-
value pairs passed to a URL by the HTTP POST method that uses URLEncoded or multipart/form-
data content-type in the request.

Assuming that the URL in the browser is "http://localhost/hello.php", method=POST is set in a


HTML form "hello.html" as below − Now,
open http://localhost
/hello.html in your
browser. You should get
the following output on
the screen −
PHP - $_GET
$_GET is one of the superglobals in PHP. It is an associative array of variables passed to the current
script via the query string appended to the URL of HTTP request. Note that the array is populated
by all requests with a query string in addition to GET requests.

By default, the client browser sends a request for the URL on the server by using the HTTP GET
method. A query string attached to the URL may contain key value pairs concatenated by the "&"
symbol. The $_GET associative array stores these key value pairs.
Save the following script in the document folder of Apache server. If you are using XAMPP server on
Windows, place the script as "hello.php" in the "c:/xampp/htdocs" folder.

Start the XAMPP server, and enter "http://localhost/hello.php?first_name=Mukesh&last_name=Sinha" as the


URL in a browser window. You should get the following output −
In your browser, enter the
URL "http://localhost/hello.html" −
PHP htmlspecialchars() Function

The browser output of the code above


will be:
This is some <b>bold</b> text.

Convert the predefined characters "<" (less than) The HTML output of the code above will be (View
and ">" (greater than) to HTML entities: Source):
<?php <!DOCTYPE html>
$str = "This is some <b>bold</b> text."; <html>
echo htmlspecialchars($str); <body>
This is some &lt;b&gt;bold&lt;/b&gt; text.
?>
</body>
</html>
PHP - $_FILES
$_FILES is one of the 'superglobal', or automatic global, variables in PHP. It is available in all scopes
throughout a script. The variable $_FILES is an associative array containing items uploaded via HTTP POST
method. The following "test.html" contains a HTML form whose enctype is set to multiform/form-data.

The server-side
PHP script
(upload.php) in
the document
root folder reads
the variables
$_FILES array as
follows −
PHP - $_ENV

$_ENV is a superglobal variable in PHP. It is an associative array that stores all the environment
variables available in the current script.
PHP - $_COOKIE

The PHP superglobal $_COOKIE stores the variables passed to the current PHP script along with
the HTTP request in the form of cookies.

What is a Cookie?
Cookies are text files stored by a server on the client computer and they are kept for tracking

purpose. PHP transparently supports HTTP cookies. Cookies are usually set in an HTTP header.

JavaScript can also sets a cookie directly on a browser.

The server script sends a set of cookies to the browser. It stores this information on the local

machine for future use. Next time, when the browser sends any request to the web server, it sends

those cookies information to the server and the server uses that information to identify the user.
The setcookie() Function
PHP provides the setcookie function to create a cookie object to be sent to the client along with the
HTTP response.

Parameters
• Name − Name of the cookie stored.
• Value − This sets the value of the named variable.
• Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
• Path − Directories for which the cookie is valid.
• Domain − Specifies the domain name in very large domains.
• Security − 1 for HTTPS. Default 0 for regular HTTP.
How to Set Cookies
Take a look at the following example. This script sets a cookie named username if it is not already set.
Example
How to Remove Cookies
To delete a cookie, set the cookie with a date that has already
expired, so that the browser triggers the cookie removal
mechanism.

Setting Cookies Using the Array Notation


You may also set the array cookies by using
the array notation in the cookie name. If the
cookie name contains dots (.), then PHP
replaces them with underscores (_).
PHP - $_SESSION
$_SESSION is an associative array of session variables available in the current script.

What is a Session?
A Session is an alternative way to make data accessible across the pages of an entire website. It is
the time duration between the time a user establishes a connection with a server and the time the
connection is terminated. During this interval, the user may navigate to different pages. Many
times, it is desired that some data is persistently available across the pages. This is facilitated
by session variables.
A session creates a file in a temporary directory on the server where the registered session
variables and their values are stored. This data will be available to all the pages on the site during
that visit.
The server assigns a unique SESSIONID to each session. Since HTTP is a stateless protocol, data in
session variables is automatically deleted when the session is terminated.
The session_start() Function
In order to enable access to session data, the session_start() function must be invoked. session_start()
creates a session or resumes the current one based on a session identifier passed via a GET or POST request,
or passed via a cookie.

Handling Session Variables


To create a new session variable, add a key-value pair in the $_SESSION array −
To read back the value of a To manually clear all the session
session variable, you can To obtain the list of all the
data, there
use echo/print statements, session variables in the
is session_destroy() function.
or var_dump() or print_r() current session, you can use
A specific session variable may
functions. a foreach loop to traverse
also be released by calling
the $_SESSION −
the unset() function.
Handling Session Variables
To create a new session variable, add a key-value pair in the $_SESSION array −

To read back the value of a session variable, To obtain the list of all the session variables in the
you can use echo/print statements, current session, you can use a foreach loop to
or var_dump() or print_r() functions. traverse the $_SESSION −
Example
The following PHP script renders an HTML
form. The form data is used to create three
session variables. A hyperlink takes the
browser to another page, which reads back
the session variables.
Save this code as "test.php" in the
document root folder, and open it in a client
browser. Enter the data and press
the Submit button.

Next, have the following script in the


"hello.php" file and save it.Now, follow the
link on the "test.php" page to navigate to
"hello.php". It will show the session
variables that are read −
PHP - Web Concepts

PHP is a server-side scripting language that is used to create dynamic webpages. It is one of the
most popular programming languages for web development. This chapter aims to let you get
familiarized with certain important concepts of web application development using PHP.

A web-based application is a collection of webpages. A webpage is mainly created with HTML tags.
HTML consists of different HTML tags which are required to define the appearance of page
elements like text, image, table, etc. Hence, HTML essentially creates a static webpage.

A Web application is hosted on a HTTP server with PHP module installed. The browser acts as a
http client, to establish communication with the server, following HTTP protocol.
Using HTML Forms
The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.

• The PHP default


variable $_PHP_SELF is used for the
PHP script name and when you
click "submit" button then same
PHP script will be called and will
produce following result −
• The method = "POST" is used to
post user data to the server
script. There are two methods of
posting data to the server script
which are discussed in PHP GET &
POST chapter.
PHP - Form Handling
HTML Forms play an important role in PHP web applications. Although a webpage composed purely
with HTML is a static webpage, the HTML form component is an important feature that helps in
bringing interactivity and rendering dynamic content. PHP’s form handling functionality can
validate data collected from the user, before processing.

An HTML Form is a collection various form controls such as text fields, checkboxes, radio buttons,
etc., with which the user can interact, enter or choose certain data that may be either locally
processed by JavaScript (client-side processing), or sent to a remote server for processing with
the help of server-side programming scripts such as PHP.

One or more form control elements are put inside <form> and </form> tags. The form element is
characterized by different attributes such as name, action, and method.
Form Attributes
Out of the many attributes of the HTML form element, the following attributes are often required
and defined −
Action Attribute
a string representing the URL that processes the form submission. For
example, http://example.com/test.php. To submit the for-data to the same PHP script in which the
HTML form is defined, use the PHP_SELF server variable −

Method Attribute
a string representing the HTTP method to submit the form with. The following methods are the
possible values of method attribute −
• post − The POST method; form data sent as the request body.
• get (default) − The GET; form data appended to the action URL with a "?" separator. Use this
method when the form has no side effects.
Form Example
Let us use these form elements to design a HTML form and send it to a PHP_SELF script
PHP & MySQL

MySQL Database Connection


Creating a Database
To create and delete a database

you should have admin privilege.

Its very easy to create a new

MySQL database. PHP

uses mysql_query function to create a

MySQL database. This function

takes two parameters and returns

TRUE on success or FALSE on

failure.
Selecting a Database
Once you establish a connection with a database server then it is required to select a particular
database where your all the tables are associated.
Creating Database Tables
To create tables in the new database you need to do the same thing as creating the database.
First create the SQL query to create the tables then execute the query using mysql_query()
function.
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and excute those commands.
Consider the following content in sql_query.txt file
Deleting MySQL Database and Table Using PHP
If a database is no longer required then it can be deleted forever. You Its again a matter of issuing one SQL command
can use pass an SQL command to mysql_query to delete a database. through mysql_query function to delete any database
table

You might also like