Вы находитесь на странице: 1из 44

UNIT - I

INTRODUCTION
HISTORY OF PHP

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

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

Though it lived a short development life, it continued to enjoy a growing popularity in still-young
world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users around the
world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains reported having headers
containing "PHP", indicating that the host server did indeed have it installed. This number equated to
approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the
maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was
still primarily developed by an individual.
What is PHP
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based software
applications. PHP scripts are executed on the server.

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


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

7PHP is an amazing and popular language , because of following reasons:

 It is powerful enough to be at the core of the biggest blogging system on the web.
 It is deep enough to run the largest social network .
 It is also easy enough to be a beginner's first server side language

PHP File

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

PHP CAN DO THE FOLLOWING :

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.
Common uses of PHP

 PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
 You add, delete, modify elements within your database thru PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.

We use PHP because of the following reasons :

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

Characteristics of PHP

Five important characteristics of PHP are :

 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity

Example code
"Hello World" Script in PHP
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential example,
first we will create a friendly little "Hello, World!" script.

As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or
XHTML if you're cutting-edge) you'll have PHP statements like this

<html>

<head>

<title>Hello World</title>

</head>

<body>

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

</body>

</html>

The output is like this


Hello, World!

PHP Data Types


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

PHP supports the following eight data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource(advanced and used for database purpose)

PHP String

A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

Exampe :

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

The output is

Hello world!
Hello world!

They are sequences of characters, like "PHP supports string operations". Following are valid examples
of string

$string_1 = "This is a string in double quotes";


$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences.

<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>

This will produce following result −

My $variable will not print!\n


My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought to be
able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two
ways by PHP −

 Certain character sequences beginning with backslash (\) are replaced with special characters

 Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -
prefixed with 0x) or octal (8-based - prefixed with 0)

In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:

Example :

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

The output is

int(5985)

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential
form.

In the following example $x is a float. The PHP var_dump() function returns the data type and
value:

Example :

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

The output is

float(10.365)

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.

They have only two possible values either true or false. PHP provides a couple of constants especially
for use as Booleans: TRUE and FALSE, which can be used like so

if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");

Interpreting other types as Booleans


Here are the rules for determine the "truth" of any value not already of the Boolean type −
 If the value is a number, it is false if exactly equal to zero and true otherwise.
 If the value is a string, it is false if the string is empty (has zero characters) or is the string "0",
and is true otherwise.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
 Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
 Don't use double as Booleans.

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:

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

The output is

array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }

PHP Object
An object is a data type which stores data and information on how to process that data.

In PHP, an object must be explicitly declared.

First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:

Example :

<?php
class Car {
function Car() {
$this->model = "VW";
}
}

// create an object
$herbie = new Car();

// show object properties


echo $herbie->model;
?>

The output is

VW

PHP NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

The output is
NULL

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.

A common example of using the resource data type is a database call.

VARIABLES

What is a variable

The main way to store information in the middle of a PHP program is by using a variable. Variables are
"containers" for storing information.

Using the variables

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.
Here are the most important things to know about variables in PHP.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance whether it
will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when necessary.
 PHP variables are Perl-like.

PHP Variable and Value Types

You will create two main types of variables in your PHP code: scalar and array. Scalar variables contain
only one value at a time, and arrays contain a list of values, or even another array.

When you assign a value to a variable, you usually assign a value of one of the following types:

 Integers. Whole numbers (numbers without decimals). Examples are 1, 345, and 9922786. You
can also use octal and hexadecimal notation: the octal 0123 is decimal 83 and the hexadecimal
0x12 is decimal 18.
 Floating-point numbers ("floats" or "doubles"). Numbers with decimals. Examples are 1.5,
87.3446, and 0.88889992.
 Strings. Text and/or numeric information, specified within double quotes (" ") or single quotes ('
').

Local and Global Variables

Variables can be local or global, the difference having to do with their definition and use by the
programmer, and where they appear in the context of the scripts you are creating.

When you write PHP scripts that use variables, those variables can be used only by the script in which
they live. Scripts cannot magically reach inside other scripts and use the variables created and defined
there—unless you say they can and you purposely link them together. When you do just that, such as
when you create your own functions (blocks of reusable code that perform a particular task), you will
define the shared variables as global. That is, you will define them as able to be accessed by other scripts
and functions, as needed.

You can learn about creating your own functions, and using global as well as local variables. For now,
just understand that there are two variable scopes—local and global—that come into play as you write
more advanced scripts.

Pre-Defined Variables

In all PHP scripts, a set of pre-defined variables is available to you. You might have seen some of these
variables in the output of the phpinfo() function, if you scrolled and read through the entire results
page. Some of these pre-defined variables are called superglobals, meaning that they are always present
and available to all of your scripts.

Flow-Control Statements
PHP supports a number of traditional programming constructs for controlling the flow of execution of a
program.

Conditional statements, such as if/else and switch, allow a program to execute different pieces of code,
or none at all, depending on some condition. Loops, such as while and for, support the repeated
execution of particular code.

1. IF

The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a
statement. An if statement looks like:

if (expression)
statement

To specify an alternative statement to execute when the expression is false, use the else keyword:

if (expression)
statement
else
statement

For example:

if ($user_validated)
echo "Welcome!";
else
echo "Access Forbidden!";

(or)
1.(a) - The if Statement

The if statement executes some code if one condition is true.

Syntax
if (condition) {
code to be executed if condition is true;
}

The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

The Output is

Have a good day!


1.(b)The if...else Statement

The if....else statement executes some code if a condition is true and another code if that
condition is false.

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

The output is
Have a good day!
2. The Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax is
switch (expression){
case label1:
code to be executed if expression = label1;
break;

case label2:
code to be executed if expression = label2;
break;
default:

code to be executed
if expression is different
from both label1 and label2;
}

Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to
match the resulting value. If a matching value is found then the code associated with the matching
label will be executed or if none of the lable matches then statement will execute any specified default
code.

<html>

<body>

<?php

$d = date("D");

switch ($d){

case "Mon":

echo "Today is Monday";

break;

case "Tue":

echo "Today is Tuesday";

break;

case "Wed":
echo "Today is Wednesday";

break;

case "Thu":

echo "Today is Thursday";

break;

case "Fri":

echo "Today is Friday";

break;

case "Sat":

echo "Today is Saturday";

break;

case "Sun":

echo "Today is Sunday";

break;

default:

echo "Wonder which day is this ?";

?>

</body>

</html>

The output is

Today is Wednesday
LOOPS

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.

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

 foreach − loops through a block of code for each element in an array.

3. While
The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test
expression will again be evaluated and the loop will continue until the test expression is found to be
false
Syntax

while (condition) {
code to be executed;
}

Example
This example decrements a variable value on each iteration of the loop and the counter increments
until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>

<?php
$i = 0;
$num = 50;

while( $i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>

</body>
</html>

The output is

Loop stopped at i = 10 and num = 40

4. The for loop statement


The for statement is used when you know how many times you want to execute a statement or a block
of statements.
Syntax

for (initialization; condition; increment){


code to be executed;
}

The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.

Example
The following example makes five iterations and changes the assigned value of two variables on each
pass of the loop

<html>
<body>

<?php
$a = 0;
$b = 0;

for( $i = 0; $i<5; $i++ ) {


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b" );


?>

</body>
</html>

The output is

At the end of the loop a = 50 and b = 25

5. The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next element
will be processed.

Syntax
foreach (array as value) {
code to be executed;
}
Example
Try out following example to list out the values of an array.

<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>

The output is

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

OPERATORS

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. PHP language supports following type of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then –

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from A - B will give -10


the first

* Multiply both operands A * B will give 200

/ Divide numerator by de- B / A will give 2


numerator

% Modulus Operator and remainder B % A will give 0


of after an integer division

++ Increment operator, increases A++ will give 11


integer value by one

-- Decrement operator, decreases A-- will give 9


integer value by one

Comparison Operators

There are following comparison operators supported by PHP language. Assume variable A holds 10 and
variable B holds 20 ,
Then we have

Operator Description Example


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

!= Checks if the value of two (A != B) is true.


operands are equal or not, if
values are not equal then
condition becomes true.

> Checks if the value of left operand (A > B) is not true.


is greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand (A < B) is true.


is less than the value of right
operand, if yes then condition
becomes true.

>= Checks if the value of left operand (A >= B) is not true.


is greater than or equal to the
value of right operand, if yes then
condition becomes true.

<= Checks if the value of left operand (A <= B) is true.


is less than or equal to the value
of right operand, if yes then
condition becomes true.

Logical Operators
There are following logical operators supported by PHP language. Assume variable A holds 10 and
variable B holds 20 , we have

Operator Description Example


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

or Called Logical OR Operator. If any (A or B) is true.


of the two operands are non zero
then condition becomes true.

&& Called Logical AND operator. If (A && B) is true.


both the operands are non zero
then condition becomes true.

|| Called Logical OR Operator. If any (A || B) is true.


of the two operands are non zero
then condition becomes true.

! Called Logical NOT Operator. Use !(A && B) is false.


to reverses the logical state of its
operand. If a condition is true
then Logical NOT operator will
make false.

Assignment Operators
There are following assignment operators supported by PHP language −

Operator Description Example


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

+= Add AND assignment C += A is equivalent to C = C + A


operator, It adds right
operand to the left operand
and assign the result to left
operand

-= Subtract AND assignment C -= A is equivalent to C = C – A


operator, It subtracts right
operand from the left
operand and assign the result
to left operand

*= Multiply AND assignment C *= A is equivalent to C = C * A


operator, It multiplies right
operand with the left
operand and assign the result
to left operand

/= Divide AND assignment C /= A is equivalent to C = C / A


operator, It divides left
operand with the right
operand and assign the result
to left operand

%= Modulus AND assignment C %= A is equivalent to C = C % A


operator, It takes modulus
using two operands and
assign the result to left.

Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or
false value and then execute one of the two given statements depending upon the result of the
evaluation. The conditional operator has this syntax −
Examples

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X :


Otherwise value Y

Operators Categories

All the operators we have discussed above can be categorized into following categories −

 Unary prefix operators, which precede a single operand.

 Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.

 The conditional operator (a ternary operator), which takes three operands and evaluates either
the second or third expression, depending on the evaluation of the first expression.

 Assignment operators, which assign a value to a variable.

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and


$txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

(i) Example program for concatenation operator is

<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
</body>
</html>

The output is “Hello world!”

(ii) Example program for concatenation assignment operator is

<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>

The output is

Hello world!

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than
+ so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left

LEXICAL STRUCTURE OF PHP

The lexical structure of a programming language is the set of basic rules that governs how you write
programs in that language. It is the lowest-level syntax of the language and specifies such things as what
variable names look like, what characters are used for comments, and how program statements are
separated from each other. Computer languages, like human languages, have a lexical structure. A
source code of a PHP script consists of tokens. Tokens are atomic code elements. In PHP language, we
have comments, variables, literals, operators, delimiters, and keywords.

Case Sensitivity

The names of user-defined classes and functions, as well as built-in constructs and keywords such as
echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent:

echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");

Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and$NaME are three different variables.

Statements and Semicolons

A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as
complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls,
assignment, and an if statement:

echo "Hello, world";


myFunction(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) {
echo "Rhyme? And Reason?";
}

PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of
code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages,
in PHP the semicolon before the closing brace is not optional:

if ($needed) {
echo "We must have it!"; // semicolon required ...

White space

White space in PHP is used to separate tokens in PHP source file. It is used to improve the readability of
the source code.

public $isRunning;

White spaces are required in some places; for example between the access specifier and the variable
name. In other places, it is forbidden. It cannot be present in variable identifiers.

$a=1;
$b = 2;
$c = 3;

The amount of space put between tokens is irrelevant for the PHP interpreter. It is based on the
preferences and the style of a programmer.
$a = 1;
$b = 2; $c = 3;
$d
=
4;
We can put two statements into one line. Or one statement into three lines. However, source code
should be readable for humans. There are accepted standards of how to lay out your source code.

Semicolon

A semicolon is used to mark the end of a statement in PHP. It is mandatory.

$a = 34;
$b = $a * 34 - 34;
echo $a;

Here we have three different PHP statements. The first is an assignment. It puts a value into
the $avariable. The second one is an expression. The expression is evaluated and the output is given to
the$b variable. The third one is a command. It prints the $a variable.

Variables

A variable is an identifier, which holds a value. In programming we say that we assign a value to a
variable. Technically speaking, a variable is a reference to a computer memory, where the value is
stored. In PHP language, a variable can hold a string, a number, or various objects like a function or a
class. Variables can be assigned different values over time.

Variables in PHP consist of the $ character, called a sigil, and a label. A label can be created from
alphanumeric characters and an underscore _ character. A variable cannot begin with a number. The
PHP interpreter can then distinguish between a number and a variable more easily.

$Value
$value2
$company_name

These were valid PHP identifiers.

$12Val
$exx$
$first-name

Keywords
A keyword is a reserved word in the PHP programming language. Keywords are used to perform a specific
task in a computer program; for example, print a value, do repetitive tasks, or perform logical operations.
A programmer cannot use a keyword as an ordinary variable.

The following is a list of PHP keywords.

abstract and array() as break


case catch class clone const
continue declare default do else
elseif enddeclare endfor endforeach endif
endswitch endwhile extends final for
foreach function global goto if
implements interface instanceof namespace new
or private protected public static
switch throw try use var
while xor

Operators

An operator is a symbol used to perform an action on some value.

+ - * / % ++ --
= += -= *= /= .= %=
== != >< > < >= <=
&& || ! xor or
& ^ | ~ . << >>

These are PHP operators.

Delimiters

A delimiter is a sequence of one or more characters used to specify the boundary between separate,
independent regions in plain text or other data stream.

$a = "PHP";
$b = 'Java';
The single and double characters are used to mark the beginning and the end of a string.

$a = array(1, 2, 3);
echo $a[1];

The square brackets are used to mark the array index.

Constants

A constant is an identifier for a value which cannot change during the execution of the script. By
convention, constant identifiers are always uppercase.

<?php
define("SIZE", 300);
define("EDGE", 100);

#SIZE = 100;

echo SIZE;
echo EDGE;

echo "\n";

?>

In the script, we define two constants.

define("SIZE", 300);
define("EDGE", 100);

Constants are created with the define() function.

Constants differ from variables; we cannot assign a different value to an existing constant. Constants do
not use the dollar sign character.
INSTALLATION PROCEDURE OF PHP

What I need for working of php

To start using PHP, you can:

 Find a web host with PHP and MySQL support


 Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.

Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.

You do not need to compile anything or install any extra tools.

Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC

However, if your server does not support PHP, you must:

 install a web server


 install PHP
 install a database, such as MySQL
UNIT –II
FUNCTIONS
PHP functions are similar to other programming languages. A function is a piece of code which takes
one more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread()etc. They are built-in functions but PHP
gives you option to create your own functions as well.

There are two parts which should be clear to you −

 Creating a PHP Function


 Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of
built-in library functions created for different area and you just need to call them according to your
requirement. The real power of PHP comes from its functions; it has more than 1000 built-in functions.

What is a function?

Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax
function functionName() {
code to be executed;
}

A function name can start with a letter or underscore (not a number). Function names are not case sensitive.
Example :
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of
the function. The function outputs "Hello world!". To call the function, just write its name:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>

The output is :
Hello world!

PHP Function Arguments/Parameters

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters
your like. These parameters work like variables inside your function. Following example takes two
integer parameters and add them together and then print them.

<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

</body>
</html>
The output is
Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is
manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original variable. You can
pass an argument by reference by adding an ampersand to the variable name in either the function call
or the function definition.

Following example depicts both the cases.

<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

The output is :
Original value is 10
Original value is 16
PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or object. return
stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to
the calling program. Note that return keyword is used to return a value from a function.

<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

The output is
Returned value from the function : 30
PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument: Consider the following example,

<!DOCTYPE html>
<html>
<body>

<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
The output is
The height is : 350
The height is : 50
The height is : 135
The height is : 80

STRINGS

A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all.
The simplest way to create a string is to enclose the string literal (i.e. string characters) in single
quotation marks ('), like this:

$my_string = 'Hello World';

You can also use double quotation marks ("). However, single and double quotation marks work in
different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings
delimited by the double quotes replaces variables with the string representations of their values as well
as specially interpreting certain escape sequences.
The escape-sequence replacements are:
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)

Example program :

<?php
$my_str = 'World';
echo "Hello, $my_str!<br>"; // Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello World!
echo 'I\'ll be back'; Displays: I'll be back
?>
PHP provides nearly one hundred functions that can manipulate strings in various ways. Some (but not
all!) of the functions that can be performed on strings are:

1. Compare Two Strings


2. Find a String In Another String
3. Find Out How Many Instances of A String Occur In Another String
4. Return Part of a String
5. Replace Part of a String
6. Trim Whitespace From The Ends of a String
7. Make An Entire String Lowercase or Uppercase
8. Convert All Applicable Characters In a String to HTML Entities, or Vice Versa
9. Strip HTML & PHP Tags From Inside of a String

There are no artificial limits on string length - within the bounds of available memory, you ought to be
able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two
ways by PHP −

 Certain character sequences beginning with backslash (\) are replaced with special characters
 Variable names (starting with $) are replaced with string representations of their values.

String Concatenation Operator


To concatenate two string variables together, use the dot (.) operator
<?php

$string1="Hello World";

$string2="1234";

echo $string1 . " " . $string2;

?>

The output is
Hello World 1234

Get The Length of a String

The PHP strlen() function returns the length of a string.

The example below returns the length of the string "Hello world!":

<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>

The output is
12
Count The Number of Words in a String

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

<!DOCTYPE html>
<html>
<body>

<?php
echo str_word_count("Hello world!");
?>

</body>
</html>
The output is
2

Using the strlen() function


The strlen() function is used to find the length of a string. Let's find the length of our string "Hello
world!":

<?php
echo strlen("Hello world!");
?>

This will produce the following result

12

The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in
the string).

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

Let's see if we can find the string "world" in our string

<?php

echo strpos("Hello world!","world");

?>

The result is 6.

Reverse a String

The PHP strrev() function reverses a string:

Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

The output of the code above will be: !dlrow olleH.

Search For a Specific Text Within a String

The PHP strpos() function searches for a specific text within a string.

If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.

The example below searches for the text "world" in the string "Hello world!":

<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("Helloworld!", "world");
?>
</body>
</html>

The output of the code above will be: 6.


String Manipulation Functions
Function Description
trim() Removes whitespace at beginning and end of a string.
ltrim() Removes whitespace at the beginning of a string.
rtrim() Removes whitespace at the end of a string.
Function Description
htmlentities() Escapes all HTML entities.
nl2br() Inserts a <br /> tag before each newline character in a string.
strtoupper() Converts a string to uppercase.
strtolower() Converts a string to lowercase.
ucfirst() Converts the first character of a string to uppercase.
ucwords() Converts the first character of each word in a string to uppercase.
Function Description
explode() Splits a string into an array on a specified character or group of characters.
Converts an array into a string, placing a specified character or group of
implode()
characters between each array element.
join() Same as implode().
Function Description
Returns the substring from the character in position pos to the end of the
substr(str,pos)
string.
Returns the substring from len characters from the end of the string to the
substr(str,-len)
end of the string.
substr(str,pos,len) Returns a len length substring beginning with the character in position pos.
Returns a substring beginning with the character in position pos and
substr(str,pos,-len)
chopping off the last len characters of the string.
If the third argument (before_needle) is false (default), then it returns the
part of the haystack from the needle on.
If the third argument (before_needle) is true, then it returns the part of the
strstr(haystack,needle,before_needle)
haystack before the needle.
The needle can be a string or an integer (or a number that can be
converted to an integer).
stristr(haystack,needle,before_needle)Same as strstr(), but case insensitive.
Finds the position of the first occurrence of a specified needle in a haystack
(string).
strpos(haystack,needle)
The needle can be a string or an integer (or a number that can be
converted to an integer).
Finds the position of the last occurrence of a specified needle in a haystack
(string).
strrpos(haystack,needle)
The needle can be a string or an integer (or a number that can be
converted to an integer).
str_replace() Replaces all occurrences of one string with another string.
substr()
As shown earlier, the substr() function behaves differently depending on the values passed to it. The following
screenshot shows the effects of using substr().
ARRAYS IN PHP

An array is a data structure that stores one or more similar type of values in a single value. For example
if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of
100 length. There are three different kind of arrays and each array value is accessed using an ID c which
is called array index.

 Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.
 Associative array − An array with strings as index. This stores element values in association with
key values rather than in a strict linear index order.
 Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices
Create an Array in PHP

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

array();

Numeric Array

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

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different
in terms of their index. Associative array will have their index as string so that you can establish a
strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the value
would be their respective salary.

Example :

<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>

</html>
This will produce the following result

Salary of mohammad is 2000


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

Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using
multiple index.

In the below example we create a two dimensional array to store marks of three students in three
subjects. This example is an associative array, you can create numeric array in the same fashion.

<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>

The output is
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

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

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

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

The output is

Вам также может понравиться