Professional Documents
Culture Documents
PHP Unit1
PHP Unit1
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
• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity
2. Features of PHP
The main features of php are:
Interpreted
Faster
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 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
Case Sensitivity
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.
if ($needed) {
echo "We must have it!"; // semicolon required ...
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
?>
// comments.php
// author Jan Bodnar
// ZetCode 2009
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.
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
$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 "\n";
?>
</body>
</html>
In our script, we assign three numeric values to three variables and print
them.
101112
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";
PHP Constants
Constants are like variables except that once they are defined they cannot
be changed or undefined.
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
Example
<?php
define("GREETING", "Welcome to PHP!", true);
echo greeting;
?>
Operators
• Arithmetic operators
+ - * / % ++ --
= += -= *= /= .= %=
== != >< > < >= <=
&& || ! xor or
& ^ | ~ . << >>
Delimiters
$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;
}
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];
/*
Author Jan Bodnar
<?php
// PHP code
?>
The <?php and ?> delimiters are used to delimit PHP code in a file.
Keywords
Data Types
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.
1998
−641
+33
Variables
Variables in PHP are identifiers prefixed with a dollar sign ($). For
example:
$name
$Age
$_debugging
$MAXIMUM_IMPACT
$what = "Fred";
$what = 35;
$what = array("Fred", 35, "Wilma");
The first time the value of a variable is set, the variable is created.
$day = 60 * 60 * 24;
echo "There are {$day} seconds in a day.\n";
A variable whose value has not been set behaves like the NULL value:
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.
PHP operators
P A Operator Operation
20 L [ Array subscript
19 R ~ Bitwise NOT
R ++ Increment
R −− Decrement
R @ Inhibit errors
17 R ! Logical NOT
16 L * Multiplication
L / Division
L % Modulus
15 L + Addition
L − Subtraction
L . String concatenation
12 N == Value equality
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
?>
(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;
?>
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
if
if (expression)statement
For example:
if ($user_validated)
echo "Welcome!";
else
echo "Access Forbidden!";
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;
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
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;
?>
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;
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.
$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
?>
<?php
$len = count($days);
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);
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.
<?php
echo "\n";
?>
$ php planets.php
<?php
$benelux = array(
'be' => 'Belgium',
'lu' => 'Luxembourg',
'nl' => 'Netherlands'
);
?>
$ php benelux.php
be is Belgium
lu is Luxembourg
nl is Netherlands
<?php
while (true) {
echo "\n";
?>
$ php testbreak.php
6 11 13 5 5 21 9 1 21 22
<?php
$num = 0;
$num++;
if (($num % 2) == 0) continue;
echo "\n";
?>
if (($num % 2) == 0) continue;