Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

PHP

UNIT 1
UNIT 1 – Introduction to PHP
Introduction to PHP
1. Features
2. Basic Syntax
1. Variable
2. Constant
3. Keywords
4. Data Types
5. Operators
6. Type casting, Type Juggling
1. Control Structure
1. Conditional Statements
2. Loops
3. Break Statements

1. Introduction

Before you start with PHP you should have a basic understanding of the
following:

• HTML
• CSS
• JavaScript

PHP is Created in 1994 by Rasmus Lerdorf. Initially php was used to


track online visitors on web.

UNIT 1 SARITA GOENKA PAGE 1


What is PHP?

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


• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
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, through email you can send data, return data to the user.
• You add, delete, modify elements within your database through
PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your
website.
• It can encrypt data.
Why PHP?

• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X,


etc.)
• PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP
resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity

UNIT 1 SARITA GOENKA PAGE 2


Why should we use PHP?
PHP can actually do anything related to server-side scripting or more
popularly known as the backend of a website.
For example, PHP can receive data from forms, generate dynamic page
content, can work with databases, create sessions, send and receive
cookies, send emails etc.
There are also many hash functions available in PHP to encrypt user’s
data that makes PHP secure and reliable to be used as a server-side
scripting language.
These are some of the abilities of PHP that makes it suitable to be used
as server-side scripting language.
PHP can run on all major operating systems like Windows, Linux, Unix,
Mac OS X etc.
Almost all of the major servers available today like Apache supports
PHP.
PHP allows using wide range of databases.
And the most important factor is that it is free to use and download
and anyone can download PHP from its official source: www.php.net.

2. Features of PHP
The main features of php are:

• It is an open source scripting language, you can freely download it


and use. PHP is a server side scripting language. It is widely used
all over the world. It is faster than other scripting languages.
• Some important features of php are given below:

UNIT 1 SARITA GOENKA PAGE 3


Simple

It is very simple and easy to use, as compared to other scripting


languages. It is widely used all over the world.

Interpreted

It is an interpreted language, i.e. there is no need for compilation.

Faster

It is faster than other scripting language e.g. asp and jsp.

Open Source

Open source means you need not pay for using php, you can freely
download and use it.

Platform Independent

PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.

Case Sensitive

PHP is case sensitive scripting language. In PHP, all keywords (e.g. if,
else, while, echo, etc.), classes, functions, and user-defined functions
are NOT case-sensitive.

Error Reporting

PHP have some predefined error reporting constants to generate a


warning or error notice.

Real-Time Access Monitoring

PHP provides access logging by creating the summary of recent accesses


for the user.

Loosely Typed Language

PHP supports variable usage without declaring its data type. It will be
taken at the time of the execution based on the type of data it has on its
value.

3. Basic Syntax
1. Variable
2. Constant
3. Keywords
4. Data Types
5. Operators

UNIT 1 SARITA GOENKA PAGE 4


6. Type casting, Type Juggling

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

UNIT 1 SARITA GOENKA PAGE 5


White space

White space in PHP is used to separate tokens in PHP source file. It is


used to improve 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.

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

Comments

Comments are used by humans to clarify the source code. All comments
in PHP follow the #character.

<?php

# comments.php
# author Jan Bodnar
# ZetCode 2009

echo "This is comments.php script\n";

?>

Everything that follows the # character is ignored by the PHP interpreter.

// comments.php
// author Jan Bodnar
// ZetCode 2009

UNIT 1 SARITA GOENKA PAGE 6


/*
comments.php
author Jan Bodnar
ZetCode 2009
*/

PHP also recognizes the comments from the C language.

Simple Example of PHP

Prog 1:

<!DOCTYPE>
<html>
<body>
<?php
echo "<h2>My First PHP Code</h2>";
?>
</body>
</html>

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

$12Val
$exx$
$first-name
UNIT 1 SARITA GOENKA PAGE 7
These were examples of invalid identifiers.

The variables are case sensitive. This means that $Price, $price,
and $PRICE are three different identifiers.

Prog 2
<!DOCTYPE>
<html>
<body>

<?php

$number = 10;
$Number = 11;
$NUMBER = 12;

echo $number, $Number, $NUMBER;

echo "\n";

?>
</body>
</html>

In our script, we assign three numeric values to three variables and print
them.

101112

This is the output of the script.

A literal

A literal is any notation for representing a value within the PHP source
code. Technically, a literal will be assigned a value at compile time, while
a variable will be assigned at runtime.

$age = 29;
$nationality = "Hungarian";

Here we assign two literals to variables. Number 29 and string Hungarian


are literals.

PHP Constants

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

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


changed during the script.

UNIT 1 SARITA GOENKA PAGE 8


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

Note: Unlike variables, constants are automatically global across


the entire script.

Create a PHP Constant

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

Syntax
define(name, value, case-insensitive)

Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false

Example

Create a constant with a case-sensitive name:


<?php
define("GREETING", "Welcome to PHP!");
echo GREETING;
?>

Example

Create a constant with a case-insensitive name:

<?php
define("GREETING", "Welcome to PHP!", true);
echo greeting;
?>

Operators

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

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

• Arithmetic operators

UNIT 1 SARITA GOENKA PAGE 9


• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators

+ - * / % ++ --
= += -= *= /= .= %=
== != >< > < >= <=
&& || ! 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.

function setDate($date) {
$this->date = $data;
}

if ($a > $b) {


echo "\$a is bigger than \$b";
}

Parentheses are used to mark the function signature. The signature is the
function parameters.

Curly brackets are used to mark the beginning and the end of the function
body. They are also used in flow control.

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

The square brackets are used to mark the array index.

/*
Author Jan Bodnar

UNIT 1 SARITA GOENKA PAGE 10


December 2009
ZetCode
*/

/* */ delimiters are used to provide C style comments in PHP.

<?php
// PHP code
?>

The <?php and ?> delimiters are used to delimit PHP code in a file.

Keywords

A keyword is a reserved word in the PHP programming language.


Keywords are used to perform a specific task in the 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

Data Types

PHP provides eight types of values, or data types.

• Four are scalar (single-value) types: integers, floating-point


numbers, strings, and Booleans.
• Two are compound (collection) types: arrays and objects.
• The remaining two are special types: resource and NULL.

UNIT 1 SARITA GOENKA PAGE 11


Integers

Integers are whole numbers, such as 1, 12, and 256. The range of
acceptable values varies according to the details of your platform but
typically extends from −2,147,483,648 to +2,147,483,647.

Specifically, the range is equivalent to the range of the long data type of
your C compiler. Unfortunately, the C standard doesn’t specify what range
that long type should have, so on some systems you might see a different
integer range.

Integer literals can be written in decimal, octal, or hexadecimal. Decimal


values are represented by a sequence of digits, without leading zeros. The
sequence may begin with a plus (+) or minus (−) sign. If there is no sign,
positive is assumed.

Examples of decimal integers include the following:

1998
−641
+33

Variables

Variables in PHP are identifiers prefixed with a dollar sign ($). For
example:

$name
$Age
$_debugging
$MAXIMUM_IMPACT

A variable may hold a value of any type. There is no compile-time or


runtime type checking on variables. You can replace a variable’s value
with another of a different type:

$what = "Fred";
$what = 35;
$what = array("Fred", 35, "Wilma");

There is no explicit syntax for declaring variables in PHP.

The first time the value of a variable is set, the variable is created.

UNIT 1 SARITA GOENKA PAGE 12


In other words, setting a value to a variable also functions as a
declaration. For example, this is a valid complete PHP program:

$day = 60 * 60 * 24;
echo "There are {$day} seconds in a day.\n";

There are 86400 seconds in a day.

A variable whose value has not been set behaves like the NULL value:

if ($uninitializedVariable === NULL) {


echo "Yes!";
}
Yes!
Expressions and Operators

An expression is a bit of PHP that can be evaluated to produce a value.


The simplest expressions are literal values and variables. A literal value
evaluates to itself, while a variable evaluates to the value stored in the
variable. More complex expressions can be formed using simple
expressions and operators.

An operator takes some values (the operands) and does something (for
instance, adds them together). Operators are written as punctuation
symbols—for instance, the + and – familiar to us from math. Some
operators modify their operands, while most do not.

Table below summarizes the operators in PHP, many of which were


borrowed from C and Perl. The column labeled “P” gives the operator’s
precedence; the operators are listed in precedence order, from highest to
lowest. The column labeled “A” gives the operator’s associativity, which
can be L (left-to-right), R (right-to-left), or N (nonassociative).

PHP operators

P A Operator Operation

21 N clone, new Create new object

20 L [ Array subscript

19 R ~ Bitwise NOT

UNIT 1 SARITA GOENKA PAGE 13


P A Operator Operation

R ++ Increment

R −− Decrement

R (int), (bool), (float), (string), (array),( Cast


object), (unset)

R @ Inhibit errors

18 N instanceof Type testing

17 R ! Logical NOT

16 L * Multiplication

L / Division

L % Modulus

15 L + Addition

L − Subtraction

L . String concatenation

14 L << Bitwise shift left

L >> Bitwise shift right

13 N <, <= Less than, less than or


equal

N >, >= Greater than, greater


than or equal

UNIT 1 SARITA GOENKA PAGE 14


P A Operator Operation

12 N == Value equality

N !=, <> Inequality

N === Type and value equality

N !== Type and value


inequality

Type Casting

Type casting in PHP works much as it does in C: the name of the desired
type is written in parentheses before the variable which is to be cast.

<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>

The casts allowed are:

o (int), (integer) - cast to integer


o (bool), (boolean) - cast to boolean
o (float), (double), (real) - cast to float
o (string) - cast to string
o (array) - cast to array
o (object) - cast to object
o (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are
functionally equivalent:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:


UNIT 1 SARITA GOENKA PAGE 15
<?php
$binary = (binary) $string;
$binary = b"binary string";
?>

Note:
Instead of casting a variable to a string, it is also possible to enclose the variable in
double quotes.
<?php
$foo = 10; // $foo is an integer
$str = "$foo"; // $str is a string
$fst = (string) $foo; // $fst is also a string
// This prints out that "they are the same"
if ($fst === $str) {
echo "they are the same";
}
?>

4. Control Structure
1. Conditional Statements
2. Loops
3. Break Statements

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 segments of code.

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:

UNIT 1 SARITA GOENKA PAGE 16


if (expression)
statement
else statement

For example:

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

To include more than one statement in an if statement, use a block—a


curly brace–enclosed set of statements:

if ($user_validated) {
echo "Welcome!";
$greeted = 1;
}
else {
echo "Access Forbidden!";
exit;
}

PHP provides another syntax for blocks in tests and loops. Instead of
enclosing the block of statements in curly braces, end the if line with a
colon (:) and use a specific keyword to end the block (endif, in this case).
For example:

if ($user_validated):
echo "Welcome!";
$greeted = 1;
else:
echo "Access Forbidden!";
exit;
endif;

UNIT 1 SARITA GOENKA PAGE 17


The switch statement

The switch statement is a selection control flow statement. It allows the


value of a variable or expression to control the flow of program execution
via a multiway branch. It creates multiple branches in a simpler way than
using the if, elseif statements.

The switch statement works with two other keywords. The case and
the break statements. The case keyword is used to test a label against a
value from the round brackets. If the label equals to the value, the
statement following the case is executed. The break keyword is used to
jump out of the switch statement. There is an optional default statement.
If none of the labels equals the value, the default statement is executed.

<?php

$domain = 'sk';

switch ($domain) {

case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}

?>

In our script, we have a $domains variable. It has the 'sk' string. We use
the switch statement to test for the value of the variable. There are several
options. If the value equals to 'us' the 'United States' string is printed to the
console.

$ php domains.php
Slovakia

We get 'Slovakia'. If we changed the $domains variable to 'rr', we would


get 'Unknown' string.

UNIT 1 SARITA GOENKA PAGE 18


The while loop

The while is a control flow statement that allows code to be executed


repeatedly based on a given boolean condition.

This is the general form of the while loop:

while (expression):
statement

The while loop executes the statement, when the expression is evaluated
to true. The statement is a simple statement terminated by a semicolon
or a compound statement enclosed in curly brackets.

<?php

$i = 0;

while ($i < 5) {


echo "PHP language\n";
$i++;
}

?>

In the code example, we print "PHP language" string five times to the
console.

The while loop has three parts: initialization, testing, and updating. Each
execution of the statement is called a cycle.

$i = 0;

We initiate the $i variable. It is used as a counter in our script.

while ($i < 5) {


...
}

The expression inside the square brackets is the second phase, the
testing. The while loop executes the statements in the body, until the
expression is evaluated to false.

$i++;

The last, third phase of the while loop. The updating. We increment the
counter. Note that improper handling of the while loops may lead to
endless cycles.

There is another version of the while loop. It is the do while loop. The
difference between the two is that this version is guaranteed to run at
least once.

UNIT 1 SARITA GOENKA PAGE 19


<?php

$count = 0;

do {
echo "$count\n";
} while ($count != 0)

?>

First the iteration is executed and then the truth expression is evaluated.

The while loop is often used with the list() and each() functions.

<?php

$seasons = array("Spring", "Summer", "Autumn", "Winter");

while (list($idx , $val) = each($seasons)) {


echo "$val\n";
}

?>

We have four seasons in a $seasons array. We go through all the values


and print them to the console. The each() function returns the current key
and value pair from an array and advances the array cursor. When the
function reaches the end of the array, it returns false and the loop is
terminated. The each() function returns an array. There must be an array
on the left side of the assignment too. We use the list() function to create
an array from two variables.

The for keyword


The for loop does the same thing as the while loop. Only it puts all three
phases, initialization, testing and updating into one place, between the
round brackets. It is mainly used when the number of iteration is know
before entering the loop.

Let's have an example with the for loop.

<?php

$days = array("Monday", "Tuesday", "Wednesday",


"Thursday", "Friday",
"Saturday", "Sunday");

$len = count($days);

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


echo $days[$i], "\n";
}

UNIT 1 SARITA GOENKA PAGE 20


?>

We have an array of days of a week. We want to print all these days from
this array. We all know that there are seven days in a week.

$len = count($days);

Or we can programmatically figure out the number of items in an array.

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


echo $days[$i], "\n";
}

Here we have the for loop construct. The three phases are divided by
semicolons. First, the $icounter is initiated. The initiation part takes place
only once. Next, the test is conducted. If the result of the test is true, the
statement is executed. Finally, the counter is incremented. This is one
cycle. The for loop iterates until the test expression is false.

The foreach statement


The foreach construct simplifies traversing over collections of data. It has
no explicit counter. Theforeach statement goes through the array one by
one and the current value is copied to a variable defined in the construct.
In PHP, we can use it to traverse over an array.

<?php

$planets = array("Mercury", "Venus", "Earth", "Mars", "Jupiter",


"Saturn", "Uranus", "Neptune");

foreach ($planets as $item) {


echo "$item ";
}

echo "\n";

?>

In this example, we use the foreach statement to go through an array of


planets.

foreach ($planets as $item) {


echo "$item ";
}

The usage of the foreach statement is straightforward. The $planets is the


array that we iterate through. The $item is the temporary variable that
has the current value from the array. The foreachstatement goes through
all the planets and prints them to the console.

$ php planets.php

UNIT 1 SARITA GOENKA PAGE 21


Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune

Running the above PHP script gives this output.

There is another syntax of the foreach statement. It is used with maps.

<?php

$benelux = array(
'be' => 'Belgium',
'lu' => 'Luxembourg',
'nl' => 'Netherlands'
);

foreach ($benelux as $key => $value) {


echo "$key is $value\n";
}

?>

In our script, we have a $benelux map. It contains domain names


mapped to the benelux states. We traverse the array and print both keys
and their values to the console.

$ php benelux.php
be is Belgium
lu is Luxembourg
nl is Netherlands

This is the outcome of the script.

The break, continue statements


The break statement is used to terminate the loop.
The continue statement is used to skip a part of the loop and continue
with the next iteration of the loop.

<?php

while (true) {

$val = rand(1, 30);


echo $val, " ";
if ($val == 22) break;

echo "\n";

?>

UNIT 1 SARITA GOENKA PAGE 22


We define an endless while loop. There is only one way to jump out of a
such loop. We must use thebreak statement. We choose a random value
from 1 to 30. We print the value. If the value equals to 22, we finish the
endless while loop.

$ php testbreak.php
6 11 13 5 5 21 9 1 21 22

We might get something like this.

In the following example, we will print a list of numbers that cannot be


divided by 2 without a remainder.

<?php

$num = 0;

while ($num < 1000) {

$num++;
if (($num % 2) == 0) continue;

echo "$num ";

echo "\n";

?>

We iterate through numbers 1..999 with the while loop.

if (($num % 2) == 0) continue;

If the expression $num % 2 returns 0, the number in question can be


divided by 2. continue statement is executed and the rest of the cycle is
skipped. In our case, the last statement of the loop is skipped and the
number is not printed to the console. The next iteration is started.

UNIT 1 SARITA GOENKA PAGE 23

You might also like