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

7.PHP Part 1

The document provides an introduction to PHP, covering its syntax, data types, and functionalities as a server-side scripting language. It discusses PHP's integration with HTML, variable declarations, outputting values, and various control structures such as if-statements and loops. Additionally, it outlines installation instructions and key features that make PHP suitable for web development.

Uploaded by

tekbwoy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

7.PHP Part 1

The document provides an introduction to PHP, covering its syntax, data types, and functionalities as a server-side scripting language. It discusses PHP's integration with HTML, variable declarations, outputting values, and various control structures such as if-statements and loops. Additionally, it outlines installation instructions and key features that make PHP suitable for web development.

Uploaded by

tekbwoy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to PHP

Part 1
Today’s Goals
Today’s lecture will cover:
Format of a PHP file
Syntax of PHP code and similarities
between PHP code and JavaScript code
Data types
Introduction
PHP: Hypertext Preprocessor
 PHP is a server-side Hypertext Markup Language
(HTML)-embedded scripting language (Sun’s Java
Server Pages and Microsoft’s Active Server Pages
PHP is an HTML-embedded scripting language.
 Its syntax is borrowed from C, Java and Perl with a
couple of unique PHP-specific features thrown in.
 The goal of the language is to allow web
developers to write dynamically generated pages
quickly.
 PHP is dynamically typed, it has no type
declarations. The type of a variable is set every
time the variable is assigned a value
Introduction
What you can do with PHP:
As a server-side scripting language, PHP is naturally
used for
 form handling and database access. Because database
access has been a prime focus of PHP development, it
has driver support for 15 different database systems.
 PHP supports the common electronic mail protocols Post
Office Protocol 3 (POP3) and
 Internet Message Access Protocol (IMAP).
 It also supports the distributed object architectures
Component Object Model (COM) and Common Object
Request Broker Architecture (CORBA).
 Create a customized user experience for visitors based
on information that you have gathered from them.
 Allow creation of shopping carts for e-commerce
websites.
Introduction – Continued
PHP has many benefits:
Open Source.
Flexible for integration with HTML – HTML easily
supports the use of the PHP scripting tags.
Suited for complex projects – database support,
vast libraries, and the power of the server allow
PHP to satisfy very complex programming needs.
Fast at running scripts – Even though PHP is a
scripting language, the architecture of the
scripting engine provides for fast execution.
Platform and O/S portable – PHP runs on a variety
of different platforms and operating systems
Installing PHP
Go to PHP.net - Downloads and download the most
recent version of PHP.
OR
Install most recent version of Wamp server or
xamp server.

For installation guide


PHP - Windows - Windows Installation Guide
PHP - Mac - Mac Installation Guide
PHP - Linux - Linux Installation Guide

Installing MySQL's
MySQL Installation Guide for help on installing
General Format of a PHP File
 There are four different 3. HTML Script Tags
Structure formants: <script language="php">
1. Default syntax echo "This is HTML script tags.";
<?php </script>
echo "Default Syntax";
?> 4. ASP Style Tags
<%
2. Short open Tags echo 'This is ASP like style';
<? %>
echo "PHP example with short-
tags";
?>

PHP Statement separation:

statements are terminated by a semicolon (;) like C or Perl.


General Format of a PHP File
(continued)

Just like JavaScript, whitespace is ignored.


Just like JavaScript, end lines with semicolon (;).
Unlike JavaScript, PHP code is executed at server and
replaced with resulting output.
The file must have the extension ".php, .php3,
or .phtml".
Server needs this in order to know to run the file through
the PHP script engine before sending output to client.

The syntax and semantics of PHP are closely related


to the syntax and semantics of JavaScript.
PHP uses dynamic typing, as does JavaScript.
Variables are not type declared, and they have no
intrinsic type.
Variable Declarations
Start it with the dollar sign ($) followed by a letter or
an underscore (_) to be a variable name. E.g.
$variable_name = Value;
Variables do not need to be declared before you use
them.

Example: $var1 = 25;
A variable can be tested to determine whether it
currently has a value using the IsSet function,
which takes the variable’s name as its parameter and
returns a Boolean value.

Example: IsSet($fruit)

Output:
TRUE if $fruit currently has a non-NULL value, FALSE
otherwise
Variable Declarations
Start it with the dollar sign ($) followed by a letter
or an underscore (_) to be a variable name. E.g.
$variable_name = Value;
Variables do not need to be declared before you
use them.

Example: $var1 = 25;
Rules for Declaring Variables:
PHP variables must start with a letter or
underscore "_".
PHP variables may only be comprised of alpha-
numeric characters and underscores. a-z, A-Z, 0-9, or _
.
Variables with more than one word should be
separated with underscores. $my_variable
Variables with more than one word can also be
Outputting Values in PHP
1. Echo “ ….”; 2. Print “ ….”;

Example: Examples:
$outputString = "The $outputString =
"Hello, World!";
answer is ";
print $outputString;
echo $outputString,
42, "!";
3. Printf
printf(literal_string,param1,param2, ...)

Examples:
$day = "Tuesday";
$high = 79;
printf("The high on %7s was %3d", $day, $high);
Outputting Values in PHP –
(Continued)
<!DOCTYPE html> Echoing Variables and Text
<html lang = "en">
Strings:
<head>
<?php
<title> today.php </title>
<meta charset = "utf-8" /> $my_string = "Hello Bob. My name
</head> is: ";
<body> echo "$my_string Bobettta <br />";
<p> echo "Hi, I'm Bob. Who are you?
<?php $my_string <br />";
print "<b>Welcome to my echo "Hi, I'm Bob. Who are you?
home page <br /> <br />"; $my_string Bobetta";
print "Today is:</b> ";
?>
print date("l, F jS");
print "<br />";
?>
</p>
</body>
</html>
PHP Reserved Words
PHP Case sensitivity

Although variable names in PHP are case sensitive,


e.g.
<?php
$amount = 200;
echo("The Amount is : $amount <br />");
echo("The Amount is : $AMOUNT <br />");
echo("The Amount is : $amoUNT <br />");
?>

reserved words and function names are not case


sensitive. For example, there is no difference
between while, WHILE, While, and wHiLe..
PHP: Single line and Multiple lines
Comments

Single line comment Multiple lines


comments
# This is a single line comment.
//This is another way of single line Example:
comment.
<?php
echo "How to make
Example:
multiline comments";
<?php
/* These are a multiline
echo "How to make single line comments
comment.";
testing, and these lines will
# This is a single line comment.
ignored
//This is another way of single line
comment. at the time of execution */
?> ?>
First PHP Script

<?php Combining PHP and HTML

echo "Hello World..."; <!DOCTYPE html>


?> <html lang="en">
<head>
<meta charset="utf-8">
<title>My First PHP
How to Save Your PHP Pages Page</title>
</head>
<body>
Use any of the following
<h1>
extensions".php, .php3, <?php
or .phtml extension, print "Hello, World!";
echo "Hello World...";
echo "Hello World...";
?>
</h1>
</body>
</html>
Data Types
Scalar types
boolean
Float/Double
integer
String

Compound types
array
object
Using Scalar Types

A boolean variable can be assigned only


values of true or false.

$answer = false;
$finished = true;

An integer is a whole number (no decimal


point)

$age = 31;
Using Scalar Types
(continued)
A float has a decimal point and may or may not have
an exponent
$price = 12.34;
$avog_num = 6.02e23; //6.02x10^23

A string is identified as a sequence of characters


$name = "John Smith";

String variables can be treated somewhat like arrays


for access to individual characters.
example, if $str has the value "apple", $str{3} is "l".

.
Strings can be concatenated using a dot ( )
$name = "John" . " Smith";
Constants
Constants are defined using the function define().
Constants associate a name with a scalar value.

define("PI", 3.141593);

There are a number of predefined constants.


These include:
M_E = 2.718281828459
M_PI = 3.1415926535898
M_2_SQRTPI = 1.1283791670955 (Square root of pi)
M_1_PI = 0.31830988618379 (Square root of 1/pi)
M_SQRT2 = 1.4142135623731 (Square root of 2)
M_SQRT1_2 = 0.70710678118655 (Square root of ½)
Arithmetic Operators

Operator Operation Example Result


+ Addition $y = 2 + 2; $y will contain 4
– Subtraction $y = 3; $y will contain 2
$y = $y – 1;
/ Division $y = 14 / 2; $y will contain 7
* Multiplication $z = 4; $y will contain 16
$y = $z * 4;
% Modulo $y = 14 % 3; $y will contain 2
++ Increment $y = 7; $y will contain 8
$y++;
-- Decrement $y = 7; $y will contain 6
$y--;
Common PHP Predefined functions that operate on
numeric
Bitwise Logical Operations

~ Bitwise NOT operator: Inverts each bit of


the
single operand placed to the right of the
symbol
& Bitwise AND: Takes the logical-bitwise
AND
of two values
| Bitwise OR operator: Takes the logical-
bitwise OR of two values
^ Bitwise XOR: Takes the logical-bitwise
exclusive-OR of two values
Bitwise Shift Operations
<< Left shift: Shifts the left operand left by the
number of places specified by the right
operand filling in with zeros on the right side.
>> Sign-propagating right shift: Shifts the left
operand right by the number of places
specified by the right operand filling in with
the sign bit on the left side.
>>> Zero-fill right shift operator: Shifts the
left operand right by the number of places
specified by the right operand filling in with
zeros on the left side.
Comparison Operators
PHP uses the eight relational operators of JavaScript.
i. > Returns true if the first value is greater than the
second
ii. >= Returns true if the first value is greater than or equal
to the second
iii. < Returns true the first value is less than the second
iv. <= Returns true if the first value is less than or equal to
the second
v. == Returns true if first value is equal to second
vi. != Returns true if first value is not equal to second
vii. === which produces TRUE only if both operands are the
same type and have the same value,
viii. !== the opposite of ===. If the types of the operands of
the other six relational operators are not the same, one is
coerced to the type of the other.
Selection Statements
The control expression can be an expression of
any type, but its value is coerced to Boolean.
The controlled statement segment can be
either a single statement or a compound
statement.
An if statement can include any number of
elseif clauses.

PHP’s if statement is like that of C.


The flow control that you learned for JavaScript
is the same for PHP.
If-Statement
The code below represents the syntax of a
typical if-statement:
if ($grade > 93)
print "Student's grade is A";

If grade was 93 or below, the computer would


simply skip this instruction.
If-Statement (continued)
Just like JavaScript, multiple instructions
may be grouped using curly brackets. For
example:

if ($grade > 93)


{
print "Student's grade is A";
$honor_roll_value = true;
}
If-Statement (continued)
As in JavaScript, the programmer can string
together if-statements to allow the computer to
select from one of a number of cases using elseif
and else. (Note that JavaScript allows else if while
PHP uses elseif.)

Example:

if ($grade > 93)


print "Student's grade is an A";
elseif ($grade > 89)
print Student's grade is an A-";
else
print "Student did not get an A";
Logical Operators
There are six Boolean operators: and, or, xor, !, &&, and ||.

! Returns true if its operand is zero or


false
&& Returns false if either operand is zero
or false
|| Returns false if both operands are zero
or false

The and and && operators perform the same operation, as do or and ||.
The difference between them is that the precedence of and and or is lower than that
of && and ||.
Switch-Statement
 The switch statement can be used as an alternative to
the if, elseif, else method.
switch($menu)
{
case 1:
print "You picked one";
break;
case 2:
print "You picked two";
break;
default:
print "You did not pick one or two";
break;
}
Switch-Statement
(continued)
Note that if a break is not encountered at the end of a
case, the processor continues through to the next case.
Example: If $var1=1, it will print both lines.

switch($var1)
{
case 1:
print "The value was 1";
default:
print "Pick another option";
break;
}
While-loop
PHP uses the while- Format:
loop just like
JavaScript. while(condition)
Like the if-statement, {
this format also uses statements to execute
a condition placed }
between two
Example:
parenthesis
As long as the
$count = 1;
condition evaluates
while($count < 72)
to true, the program {
continues to execute print "$count ";
the code between the $count++;
curly brackets in a }
round-robin fashion.
do … while
The do … while loop works the same as a while loop
except that the condition is evaluated at the end of
the loop rather than the beginning
Example:

$count = 1;
do
{
print "$count ";
$count++;
}while($count < 72);
for-loop
In the two previous cases, a counter was used
to count our way through a loop.
This task is much better suited to a for-loop.

for ($count = 1; $count < 72; $count++)


{
print "$count ";
}

A "break" can be used to break out of a loop


earlier.
Escape Characters
Because of the number of reserved characters in
PHP, escaping is necessary.
Characters are escaped by preceding them with a
backslash (\).
Characters that need escaped include ', ", \, $, and ?.
Whitespace including carriage returns are allowed as
part of a string, but they are then output as part of the
string.
As in JavaScript, single quotes can be used without
escaping within double quoted strings and vice versa.
Escaping can also be used to display
ISO-8859-1 characters that are not present on the
keyboard.
This is done by taking the ISO-8859-1 hex value and placing
it after "\x".
In-Class Exercise
Identify the errors in the following PHP script.
<?php
strvar1 = "<h1 align="center">Integer
Squares from 0 to 9</h1>"
prints strvar
prints "<ul>"
for(i = 0; i < 9; i+)
{
isquared = i * i
prints "<li>Square root of " + i +
" is " + isquared + "</li>"
}
prints "</ul>"
?>

You might also like