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

WEB DESIGN PROGRAMMING : CHAPTER 4

( PHP: Programming Introduction) ----JITENDRA SINGH

INTRODUCTION  PHP can send and receive


cookies
 PHP can add, delete, modify
What is PHP? data in your database
 PHP can be used to control
 PHP is an acronym for "PHP: user-access
Hypertext Preprocessor"  PHP can encrypt data
 PHP is a widely-used, open
source scripting language With PHP you are not limited to
 PHP scripts are executed on output HTML. You can output
the server images, PDF files, and even Flash
 PHP is free to download and movies. You can also output any
use text, such as XHTML and XML.

PHP is an amazing and popular


language!
Why PHP?
It is powerful enough to be at the  PHP runs on various platforms
core of the biggest blogging system (Windows, Linux, Unix, Mac
on the web (WordPress)! OS X, etc.)
It is deep enough to run the largest  PHP is compatible with almost
social network (Facebook)! all servers used today
It is also easy enough to be a (Apache, IIS, etc.)
beginner's first server side language!  PHP supports a wide range of
databases
 PHP is free. Download it from
What is a PHP File? the official PHP
resource: www.php.net
 PHP files can contain text,  PHP is easy to learn and runs
HTML, CSS, JavaScript, and efficiently on the server side
PHP code
 PHP code are executed on the
server, and the result is
Basic PHP Syntax
returned to the browser as
plain HTML A PHP script can be placed anywhere
 PHP files have extension in the document.
".php"
A PHP script starts with <?php and
ends with ?>:
What Can PHP Do?
<?php
 PHP can generate dynamic // PHP code goes here
page content ?>
 PHP can create, open, read,
write, delete, and close files The default file extension for PHP
on the server files is ".php".
 PHP can collect form data
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

A PHP file normally contains HTML EcHo "Hello World!<br>";


tags, and some PHP scripting code. ?>

Below, we have an example of a </body>


simple PHP file, with a PHP script </html>
that uses a built-in PHP function

PHP Variables
"echo" to output the text "Hello
World!" on a web page:

<!DOCTYPE html> In PHP, a variable starts with the $


<html> sign, followed by the name of the
<body> variable:

<h1>My first PHP page</h1>


Example
<?php <?php
echo "Hello World!"; $txt = "Hello world!";
?> $x = 5;
$y = 10.5;
</body> ?>
</html>

OUTPUT: After the execution of the


statements above, the
variable $txt will hold the
My first PHP page value Hello world!, the
variable $x will hold the value 5,
Hello World! and the variable $y will hold the
value 10.5.
PHP Case Sensitivity Note: When you assign a text value
to a variable, put quotes around the
In PHP, all keywords (e.g. if, else, value.
while, echo, etc.), classes, functions,
and user-defined functions are NOT Note: Unlike other programming
case-sensitive. languages, PHP has no command for
declaring a variable. It is created the
In the example below, all three echo moment you first assign a value to
statements below are legal (and it.
equal):
Think of variables as containers for
<!DOCTYPE html> storing data.
<html>

PHP Variables
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

A variable can have a short name


(like x and y) or a more descriptive
Example
name (age, carname, total_volume). <?php
$txt = " PHP Language";
Rules for PHP variables:
echo "I love " . $txt . "!";
?>
 A variable starts with the $
sign, followed by the name of
The following example will output
the variable
 A variable name must start the sum of two variables:
with a letter or the underscore
character Example
 A variable name cannot start
with a number <?php
 A variable name can only $x = 5;
contain alpha-numeric $y = 4;
characters and underscores echo $x + $y;
(A-z, 0-9, and _ ) ?>
 Variable names are case-

PHP is a Loosely
sensitive ($age and $AGE are
two different variables)

Remember that PHP variable names Typed Language


are case-sensitive!
In the example above, notice that
Output Variables we did not have to tell PHP which
data type the variable is.

The PHP echo statement is often PHP automatically converts the


used to output data to the screen. variable to the correct data type,
depending on its value.
The following example will show how
to output text and a variable: In other languages such as C, C++,
and Java, the programmer must
Example declare the name and type of the
variable before using it.
<?php
$txt = "PHP Language";
echo "I love $txt!";
PHP String Functions
Get The Length of a
?>

The following example will produce


the same output as the example String
above:
The PHP strlen() function returns the
length of a string.
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

The example below returns the The output of the code above will
length of the string "Hello world!": be: !dlrow olleH.

Example Search For a Specific


<?php
echo strlen("Hello world!"); //
Text Within a String
outputs 12
?> The PHP strpos() function searches
for a specific text within a string.
The output of the code above will
be: 12. If a match is found, the function
returns the character position of the
first match. If no match is found, it
Count The Number will return FALSE.

of Words in a String The example below searches for the


text "world" in the string "Hello
world!":
The PHP str_word_count() function
counts the number of words in a
string: Example
Example <?php
echo strpos("Hello
<?php world!", "world"); // outputs 6
echo str_word_count("Hello ?>
world!"); // outputs 2
Tip: The first character position in a
?>
string is 0 (not 1).
The output of the code above will
be: 2. Replace Text Within a
Reverse a String String
The PHP strrev() function reverses a The PHP str_replace() function
string: replaces some characters with some
other characters in a string.

Example The example below replaces the text


"world" with "Dolly":
<?php

Example
echo strrev("Hello world!"); //
outputs !dlrow olleH
?>
<?php
echo str_replace("world", "Dolly",
"Hello world!"); // outputs Hello
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

Dolly!
?>
- Subtracti $x - Differe Sh
The output of the code above will on $y nce of ow
$x and it »
be: Hello Dolly!
$y

PHP Operators
* Multiplic $x * Produc Sh
Operators are used to perform
ation $y t of $x ow
operations on variables and values.
and $y it »
PHP divides the operators in the
following groups:
/ Division $x / Quotie Sh
 Arithmetic operators
$y nt of ow
 Assignment operators
$x and it »
 Comparison operators
$y
 Increment/Decrement
operators
 Logical operators
 String operators
% Modulus $x % Remai Sh
 Array operators
$y nder of ow
$x it »
PHP Arithmetic divided
by $y
Operators
The PHP arithmetic operators are ** Exponen $x ** Result
used with numeric values to perform tiation $y of
common arithmetical operations, raising
such as addition, subtraction, $x to
multiplication etc. the
$y'th
power
Oper Name Exa Result (Introd
ator mple uced in
PHP
5.6)

+ Addition $x + Sum of Sh
$y $x and ow
$y it »
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

PHP Assignment »

Operators
x /= y x= Division Sho
The PHP assignment operators are x/y w it
used with numeric values to write a »
value to a variable.

The basic assignment operator in


PHP is "=". It means that the left x %= y x= Modulus Sho
operand gets set to the value of the x% w it
assignment expression on the right. y »

Assignme
nt
Sam Descriptio
e n PHP Comparison
as...
Operators
The PHP comparison operators are
x=y x= The left Sho used to compare two values
y operand w it (number or string):
gets set to »
the value
of the
Operat Name Exam Resu
expression
or ple lt
on the
right

== Equal $x == Retur Sho


$y ns w it
x += y x= Addition Sho
true »
x+ w it
if $x
y »
is
equal
to $y
x -= y x= Subtractio Sho
x-y n w it
»
=== Identi $x Retur Sho
cal === ns w it
$y true »
if $x
x *= y x= Multiplicati Sho
is
x * y on w it
equal
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

to $y,
and > Great $x > Retur Sho
they er $y ns w it
are of than true »
the if $x
same is
type great
er
than
$y
!= Not $x != Retur Sho
equal $y ns w it
true »
if $x < Less $x < Retur Sho
is not than $y ns w it
equal true »
to $y if $x
is
less
than
<> Not $x <> Retur Sho $y
equal $y ns w it
true »
if $x
is not >= Great $x >= Retur Sho
equal er $y ns w it
to $y than true »
or if $x
equal is
to great
!== Not $x !== Retur Sho er
identic $y ns w it than
al true » or
if $x equal
is not to $y
equal
to $y,
or
they <= Less $x <= Retur Sho
are than $y ns w it
not of or true »
the equal if $x
same to is
type less
than
or
equal
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

to $y nt decrement »
s $x by
one

PHP Increment /
PHP Logical
Decrement Operators
Operators
The PHP increment operators are
used to increment a variable's value. The PHP logical operators are used
to combine conditional statements.
The PHP decrement operators are
used to decrement a variable's
value.
Operat Nam Examp Resu
or e le lt

Operat Name Descripti


or on
and And $x and True Sho
$y if w it
both »
++$x Pre- Increment Sho $x
increme s $x by w it and
nt one, then » $y
returns $x are
true

$x++ Post- Returns Sho


increme $x, then w it or Or $x or True Sho
nt increment » $y if w it
s $x by either »
one $x or
$y is
true

--$x Pre- Decremen Sho


decreme ts $x by w it
nt one, then » xor Xor $x xor True Sho
returns $x $y if w it
either »
$x or
$y is
$x-- Post- Returns Sho true,
decreme $x, then w it but
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

not
both . Concate $txt1 Concate Sh
nation . nation ow
$txt2 of $txt1 it
and »
&& And $x && True Sho $txt2
$y if w it
both »
$x
and .= Concate $txt1 Append Sh
$y nation .= s $txt2 ow
are assignm $txt2 to $txt1 it
true ent »

|| Or $x || True Sho
$y if w it
either »
$x or PHP Array Operators
$y is
true The PHP array operators are used to
compare arrays.

! Not !$x True Sho


Opera Name Exam Resul
if $x w it
tor ple t
is not »
true

+ Union $x + Union Sho


$y of $x w it
and $y »

PHP String Operators


PHP has two operators that are == Equalit $x == Return Sho
specially designed for strings. y $y s true w it
if $x »
and $y
have
Oper Name Exa Result the
ator mple same
key/va
lue
pairs
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

=== Identit $x Return Sho


PHP Conditional
y ===
$y
s true w it
if $x »
Statements
and $y
have Very often when you write code, you
the want to perform different actions for
same different conditions. You can use
key/va conditional statements in your code
lue to do this.
pairs
in the In PHP we have the following
same conditional statements:
order
and of  if statement - executes some
the code if one condition is true
same  if...else statement -
types executes some code if a
condition is true and another
code if that condition is false
 if...elseif....else statement -
!= Inequa $x != Return Sho executes different codes for
lity $y s true w it more than two conditions
if $x is »  switch statement - selects
not one of many blocks of code to
equal be executed
to $y

<> Inequa $x <> Return Sho PHP - The if


lity $y s true w it
if $x is » Statement
not
equal The if statement executes some
to $y code if one condition is true.

Syntax
!== Non- $x Return
identit !== s true if (condition) {
y $y if $x is code to be executed if
not condition is true;
identic }
al to
$y The example below will output "Have
a good day!" if the current time
(HOUR) is less than 20:
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

Example
}
?>
<?php

PHP - The
$t = date("H");

if ($t < "20") {

}
echo "Have a good day!"; if...elseif....else
?>
Statement

PHP - The if...else The if....elseif...else statement


executes different codes for more

Statement
than two conditions.

The if....else statement executes


Syntax
some code if a condition is true and if (condition) {
another code if that condition is code to be executed if this
false.
condition is true;
} elseif (condition) {
Syntax code to be executed if this
condition is true;
if (condition) { } else {
code to be executed if code to be executed if all
condition is true; conditions are false;
} else { }
code to be executed if
condition is false; The example below will output "Have
} a good morning!" if the current time
is less than 10, and "Have a good
The example below will output "Have day!" if the current time is less than
a good day!" if the current time is 20. Otherwise it will output "Have a
less than 20, and "Have a good good night!":
night!" otherwise:

Example
Example
<?php
<?php $t = date("H");
$t = date("H");
if ($t < "10") {
if ($t < "20") { echo "Have a good morning!";
echo "Have a good day!"; } elseif ($t < "20") {
} else { echo "Have a good day!";
echo "Have a good night!"; } else {
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

echo "Have a good night!"; The example below first sets a


} variable $x to 1 ($x = 1). Then, the
?> while loop will continue to run as
long as $x is less than, or equal to 5

PHP Loops ($x <= 5). $x will increase by 1


each time the loop runs ($x++):

Often when you write code, you


want the same block of code to run
Example
over and over again in a row. <?php
Instead of adding several almost
$x = 1;
equal code-lines in a script, we can
use loops to perform a task like this.
while($x <= 5) {
In PHP, we have the following echo "The number is: $x <br>";
looping statements: $x++;
}
 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 The PHP do...while
specified condition is true
 for - loops through a block of
code a specified number of
Loop
times
The do...while loop will always
 foreach - loops through a
execute the block of code once, it
block of code for each element
will then check the condition, and
in an array
repeat the loop while the specified
condition is true.

Syntax
The PHP while Loop do {
code to be executed;
The while loop executes a block of
code as long as the specified } while (condition is true);
condition is true.
The example below first sets a
variable $x to 1 ($x = 1). Then, the
Syntax do while loop will write some output,
and then increment the variable $x
while (condition is true) { with 1. Then the condition is checked
code to be executed; (is $x less than, or equal to 5?), and
} the loop will continue to run as long
as $x is less than, or equal to 5:
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

Example
code to be executed;
}
<?php
$x = 1; Parameters:

 init counter: Initialize the loop


do {
counter value
echo "The number is: $x <br>";
 test counter: Evaluated for
$x++;
each loop iteration. If it
} while ($x <= 5); evaluates to TRUE, the loop
?> continues. If it evaluates to
FALSE, the loop ends.
Notice that in a do while loop the  increment counter: Increases
condition is tested AFTER executing the loop counter value
the statements within the loop. This
means that the do while loop would The example below displays the
execute its statements at least once, numbers from 0 to 10:
even if the condition is false the first
time.
Example
The example below sets the $x
<?php
variable to 6, then it runs the
loop, and then the condition is for ($x = 0; $x <= 10; $x++) {
checked: echo "The number is: $x <br>";
}

Example
?>

<?php
$x = 6;

do {
The PHP foreach
echo "The number is: $x <br>";
$x++;
Loop
} while ($x <= 5);
?> The foreach loop works only on
arrays, and is used to loop through
each key/value pair in an array.
The PHP for Loop
Syntax
The for loop is used when you know
in advance how many times the foreach ($array as $value) {
script should run. code to be executed;
}
Syntax
For every loop iteration, the value of
for (init counter; test counter; the current array element is
increment counter) { assigned to $value and the array
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

pointer is moved by one, until it different from all labels;


reaches the last array element. }

The following example demonstrates This is how it works: First we have a


a loop that will output the values of single expression n (most often a
the given array ($colors): variable), that is evaluated once.
The value of the expression is then
Example compared with the values for each
case in the structure. If there is a
<?php match, the block of code associated
$colors with that case is executed.
= array("red", "green", "blue", "ye
Use break to prevent the code from
running into the next case
llow");
automatically.
The default statement is used if no
foreach ($colors as $value) {
match is found.
echo "$value <br>";
}
?> Example

The PHP switch


<?php
$favcolor = "red";

Statement switch ($favcolor) {


case "red":
Use the switch statement to select echo "Your favorite color
one of many blocks of code to be is red!";
executed. break;
case "blue":

Syntax echo "Your favorite color


is blue!";
switch (n) { break;
case label1: case "green":
code to be executed if echo "Your favorite color
n=label1; is green!";
break; break;
case label2: default:
code to be executed if echo "Your favorite color
n=label2; is neither red, blue, nor green!";
break; }
case label3: ?>
code to be executed if
n=label3;
break; PHP Arrays
...
default: An array stores multiple values in
code to be executed if n is one single variable:
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

Example In PHP, the array() function is used


to create an array:
<?php
array();
$cars
= array("Volvo", "BMW", "Toyota");
In PHP, there are three types of
echo "I like " . $cars[0] . ", " .
arrays:
$cars[1] . " and " . $cars[2]
. ".";  Indexed arrays - Arrays with
?> a numeric index
 Associative arrays - Arrays
with named keys
What is an Array?  Multidimensional arrays -
Arrays containing one or more
arrays
An array is a special variable, which
can hold more than one value at a
time.

If you have a list of items (a list of


car names, for example), storing the
PHP Indexed Arrays
cars in single variables could look
There are two ways to create
like this:
indexed arrays:
$cars1 = "Volvo";
$cars2 = "BMW";
The index can be assigned
automatically (index always starts at
$cars3 = "Toyota";
0), like this:
However, what if you want to loop $cars = array("Volvo", "BMW",
through the cars and find a specific "Toyota");
one? And what if you had not 3 cars,
but 300?
or the index can be assigned
manually:
The solution is to create an array!
$cars[0] = "Volvo";
An array can hold many values
$cars[1] = "BMW";
under a single name, and you can
$cars[2] = "Toyota";
access the values by referring to an
index number.
The following example creates an
indexed array named $cars, assigns
three elements to it, and then prints
a text containing the array values:
Create an Array in
Example
PHP <?php
$cars
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

= array("Volvo", "BMW", "Toyota"); for($x = 0; $x < $arrlength; $x++)


echo "I like " . $cars[0] . ", " . {
$cars[1] . " and " . $cars[2] echo $cars[$x];
. "."; echo "<br>";
?> }
?>

Get The Length of an


PHP Associative
Array - The count()
Arrays
Function
Associative arrays are arrays that
The count() function is used to use named keys that you assign to
return the length (the number of them.
elements) of an array:
There are two ways to create an
associative array:
Example
$age = array("Peter"=>"35",
<?php
"Ben"=>"37", "Joe"=>"43");
$cars
= array("Volvo", "BMW", "Toyota");
or:
echo count($cars);
?> $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

Loop Through an The named keys can then be used in


a script:

Indexed Array Example


To loop through and print all the <?php
values of an indexed array, you $age
could use a for loop, like this: = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
Example echo "Peter is " . $age['Peter']
. " years old.";
<?php ?>
$cars
= array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
WEB DESIGN PROGRAMMING : CHAPTER 4
( PHP: Programming Introduction) ----JITENDRA SINGH

Loop Through an
Associative Array
To loop through and print all the
values of an associative array, you
could use a foreach loop, like this:

Example
<?php
$age
= array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" .
$x_value;
echo "<br>";
}
?>

You might also like