Unit 2 Working With Basic Building Blocks of PHP
Unit 2 Working With Basic Building Blocks of PHP
2
2.7 PHP Variable and value types, data types, changing types with
settype(), casting
2.8 PHP Operators (Arithmetic, Logical, Bitwise, Assignment,
String, Inc/ Decrement, Comparison)
2.9 Operator precedence, constants, predefined constants
3
2.1 INTRODUCTION TO PHP
PHP is an acronym for "PHP: Hypertext Preprocessor“.
PHP is a widely-used, open source scripting language.
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“.
4
WHAT CAN PHP DO?
PHP can generate dynamic page content.
PHP can create, open, read, write, delete, and close files
on the server.
PHP can collect form data.
5
PHP runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.)
6
WAMP, LAMP & XAMPP SERVER
WAMP Server
LAMP Server
8
2.2 A BRIEF HISTORY OF PHP
PHP Created in 1994 by Rasmus Lerdorf, the very first
incarnation of PHP was a 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,"
In June of 1995, 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& its give the
name of PHP1.0.
Zeev Suraski and Andi Gutmans rewrote the parser in 1997
and formed the base of PHP 3, changing the language's name
to the recursive acronym PHP: Hypertext
Preprocessor. Afterwards, public testing of PHP 3 began, and
the official launch came in June 1998. 9
Suraski and Gutmans then started a new rewrite of PHP's core
it release Version PHP 2.0.In year 1998 they release new
version of PHP & it is known as PHP version 3.0.
After they release of PHP Version 3.0 Zeev Suraski and Andi
Gutmans add various feature to the exiting version of PHP
such as session handling,output buffering etc..& release a
PHP version 4.0
PHP version 4.0 does not support full Object Oriented
Programming features.Finally the PHP Version 5.0 was
release in 2004 with Object Oriented Programming Concept.
10
2.3 HOW PHP WORKS?, PHP FILE STRUCTURE, PHP
START AND END TAGS, COMMENTING CODES ( SINGLE
LINE, MULTI LINE)
11
12
PHP START AND END TAGS
To execute the php script it must be written between php start
tag and eng tag.
If it is not written between start tag and end tag then server
will not execute the php script.
PHP support four types of start and end tag.
Sr.
Tag Type Start Tag End Tag
No.
14
COMMENTING CODES ( SINGLE LINE, MULTI
LINE)
15
EXAMPLE OF COMMENT IN PHP
<!DOCTYPE html>
<html> // You can also use comments
<body> to leave out parts of a code
<?php line
// This is a single-line $x = 5 /* + 15 */ + 5;
comment echo $x;
# This is also a single-line ?>
comment </body>
/* </html>
This is a multiple-lines
comment block
that spans over multiple lines
*/ 16
2.4 CREATING AND SAVING A PHP FILE
<?php
// PHP code goes here
?>
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html> 18
NOTE
PHP statements end with a semicolon (;).
In PHP, all keywords (e.g. if, else, while, echo, etc.),
classes, functions, and user-defined functions are NOT
case-sensitive.
However; all variable names are case-sensitive.
19
2.5 OUTPUT STATEMENT, ECHO AND PRINT
STATEMENT
echo statement
print statement
20
ECHO STATEMENT
21
Example
<?php
echo "<h2>PHP is Fun!</h2>”;
echo "Hello world! ",“ Good Morning";
echo “<br>I'm about to learn PHP!";
?>
22
PRINT STATEMENT
As a statement
print “Welcome to PHP”;
As a function
print (“Welcome to PHP”);
The print statement accepts only one string as an argument and
display it on browser.
The print statement always return 1.
23
Example
<?php
print "<h2>PHP is Fun!</h2>”;
print "Hello world! “.“ Good Morning";
print ( “<br>I'm about to learn PHP!“);
?>
24
2.6 INSTALLING PHP FOR (WINDOWS, WAMP
SERVER , LINUX , LAMP SERVER, XXAMP
SERVER), CONFIGURING APACHE TO USE PHP,
TESTING THE PHP INSTALLATION
If you decide to download PHP and install it
manually the step is below.
1. Download PHP and the WinCache extension.
2. Install PHP and WinCache.
3. Add the PHP installation folder to the Path environment
variable.
4. Set up a handler mapping for PHP.
5. Add default document entries for PHP.
6. Test your PHP installation.
25
Installing PHP for wamp server
1. Download the WAMP Server
28
CONFIGURING APACHE TO USE PHP, TESTING
THE PHP INSTALLATION
Now that we have configured PHP to work as we want it, lets go to
Apache and do the same.
Open httpd.conf. and in the "Dynamic Shared Object (DSO) Support"
section add the following directives (if you have located your PHP
folder differently do make corresponding change for
php5apache2_2.dll below):
LoadModule php5_module "C:/Program
Files/PHP/php5apache2_2.dll" AddType application/x-httpd-php .php
In the DirectoryIndex add index.php and index.htm as possible files
to serve when directory is requested as follows DirectoryIndex
index.html index.htm index.php .
At the end of the file add the following line which will point out
where the php.ini file is locatedPHPIniDir "C:/Program Files/PHP"29
Restart and test PHP
As soon as you make any change to any of php.ini or httpd.conf or
any other configuration files you need to restart Apache to see the
actual effect of the changes. So lets now restart Apache by using
the Apache Monitor tool you can find in your Windows status bar.
Hopefully you are not prompted with any dialogues and the
Apache Monitor continues to run green.
We will now make a test that PHP is working. Go to your web
servers document root (in the default case C:\Program
Files\Apache Software Foundation\Apache2.2\htdocs) and add a
file called phpinfo.php with the following content:
<?php phpinfo(); phpinfo(INFO_MODULES); ?> This will render
a page containing information about your PHP setup and about the
various modules/extensions that are currently loaded.
30
2.7 USE PHP VARIABLES, DATA TYPES AND
OPERATORS.
PHP variables
A variable is memory location which is used to store
value.
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the
variable
A variable name must start with a letter or the underscore
character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two
different variables) 31
33
Datatype Use
Gettype( ) function
In PHP, gettype( ) function is used to get the datatype of
variable.
Syntax:
gettype(variable name);
Example:
<? php
$a=10;
echo gettype($a);
?>
Output:
Integer
35
SETTYPE( ) FUNCTION
In PHP, settype( ) function is used to set the datatype of variable.
It returns Boolean value.
If variable is set successfully to specific type then it returns 1
otherwise 0.
Syntax:
settype(variable name, datatype);
Example:
<?php
$a;
echo settype($a,”Integer”);
echo gettype($a);
echo $a;
?>
Output: 36
Integer
0
TYPE CASTING
Type casting is used to change the datatype of variable but
the difference is that casting produces a copy of existing
variable and changes datatype of newly created variable.
The datatype of existing variable remains as it is.
Syntax:
$NewVariable = (Datatype) $OldVariable;
37
Example:
<?php
$a=10;
$b = (float) $a;
echo gettype($a);
echo gettype($b);
?>
Output
Integer
Double
38
2.8 DESCRIBE PHP OPERATORS
Operators are used to perform operations on variables
and values.
PHP divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
39
1. ARITHMETIC OPERATORS
The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
It means that the left operand gets set to the value of the
assignment expression on the right.
Equal
Assignment Meaning
to…
x=y $x + $y Sum of $x and $y
x += y $x - $y Difference of $x and $y
* $x * $y Product of $x and $y
/ $x / $y Quotient of $x and $y
41
% $x % $y Remainder of $x divided by $y
** $x ** $y Result of raising $x to the $y'th power
3. COMPARISON OPERATORS
The PHP comparison operators are used to compare two values
(number or string).
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
4. LOGICAL OPERATORS
The PHP logical operators are used to combine
conditional statements.
44
6. INCREMENT/DECREMENT OPERATORS
The PHP increment operators are used to increment a
variable's value.
The PHP decrement operators are used to decrement a
variable's value.
Syntax:
<?php
$r=10;
define(“PI", 3.14);
echo “Area = ” . PI*$r*$r;
?>
48
2D. APPLY CONTROL STRUCTURES IN
PROGRAMMING
2.10 FLOW CONTROL STATEMENTS: THE SIMPLE
IF STATEMENT, THE IF-ELSE STATEMENT, ELSE IF
CLAUSE, SWITCH STATEMENT, THE ? OPERATOR
In PHP we have the following conditional statements:
if statement - executes some code only if a specified
condition is true
if...else statement - executes some code if a condition is
true and another code if the condition is false
if...elseif....else statement - specifies a new condition to
test, if the first condition is false
switch statement - selects one of many blocks of code 49 to
be executed
IF STATEMENT
The if statement is used to execute some code only if a
specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
Example
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
} 50
?>
THE IF...ELSE STATEMENT
Use the if....else statement to execute some code if a condition
is true and another code if the condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
51
Example
<?php
$a = 10;
if ($a%2 == 0)
{
echo “a is even number";
}
else
{
echo “a is odd number";
}
?>
52
THE IF...ELSEIF....ELSE STATEMENT
Use the if....else if...else statement to specify a new condition
to test, if the first condition is false.
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
} 53
Example
<?php
$a = 10;
if ($a < 0)
{
echo “a is negative number";
}
else if ($a >0)
{
echo " a is positive number ";
}
else
{
echo " a is zero";
}
54
?>
THE SWITCH STATEMENT
Use the switch statement to select one of many blocks of code
to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
...
default:
code to be executed if n is different from all labels;
} 55
First we have a single expression n (most often a variable),
that is evaluated once.
The value of the expression is then compared with the values
for each case in the structure.
If there is a match, the block of code associated with that case
is executed.
Use break to prevent the code from running into the next case
automatically.
The default statement is used if no match is found.
56
Example
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
} 57
?>
2.11 LOOPS: THE WHILE STATEMENT, DO..
WHILE STATEMENT, FOR STATEMENT,
BREAKING OUT WITH BREAK STATEMENT,
CONTINUE STATEMENT, NESTING LOOPS.
PHP Loops
If you want the same block of code to run over and over
again in a row.
Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
58
PHP LOOPS
In PHP, we have the following looping statements:
while - loops through a block of code as long as
the specified condition is true
do...while - loops through a block of code once,
and then repeats the loop as long as the specified
condition is true
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
59
WHILE LOOP
The while loop executes a block of code as long as the specified
condition is true.
Syntax
while (condition is true)
{
code to be executed;
}
Example
<?php
$x = 1;
while($x <= 5)
{
Echo "The number is: $x <br>";
$x++;
}
?> 60
DO...WHILE LOOP
The do...while loop will always execute the block of code once,
it will then check the condition, and repeat the loop while the
specified condition is true.
Syntax
do
{
code to be executed;
}while (condition is true);
In a do while loop the condition is tested AFTER executing the
statements within the loop.
This means that the do while loop would execute its statements
at least once, even if the condition is false the first time.
61
Example:
<?php
$x = 6;
do
{
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
62
FOR LOOP
PHP for loops execute a block of code a specified number of times.
The for loop is used when you know in advance how many times
the script should run.
Syntax
64
BREAKING OUT WITH BREAK STATEMENT
break statement is used inside loop to transfer control
of script immediately after the loop either
conditionally or unconditionally.
If we write break statement inside the nested loop
then it will transfer control of the script outside loop
in which it exits.
Example
<?php
for($i;$i<=10;$i++)
{
if ($i%5==0)
break;
else
echo $i.”<br>”;
}
?> 65
CONTINUE STATEMENT
It is required to skip the execution of some statements inside the
loop.
Continue statement allows to skip the statement that appear
immediately after it & transfer the control of the script to the next
iteration in the loop.
It is used to inside for,while or do…while loop.
Example
<?php
for($i;$i<=10;$i++)
{
if ($i%2==0)
continue;
else
echo $i.”<br>”;
}
66
?>
NESTING LOOPS
When one loop is contained another loop then it is called as Nested Loop.
Generally nested loops are used with 2-dimensional Array & Matrix
Representation.
It is also used to display the information of Tablear form in row & column
wise data display.
Example
<?php
for($i=1;$i<=5;$i++)
{
for($j=1;$j<=5;$j++)
{
echo $i * $j;
echo “ “;
}
echo “<br>”;
} 67
?>