[go: up one dir, main page]

0% found this document useful (0 votes)
60 views18 pages

Asma - WP - Chapter 6 - PHP

This document provides an introduction to PHP, including: PHP is an open source scripting language used for web development and can be embedded into HTML. It allows for dynamic content, databases, sessions, and building e-commerce sites. PHP supports many databases and protocols. To use PHP, a web server, database, and PHP parser need to be installed. The document then discusses PHP variables, operators, and gives a basic "Hello World" example.

Uploaded by

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

Asma - WP - Chapter 6 - PHP

This document provides an introduction to PHP, including: PHP is an open source scripting language used for web development and can be embedded into HTML. It allows for dynamic content, databases, sessions, and building e-commerce sites. PHP supports many databases and protocols. To use PHP, a web server, database, and PHP parser need to be installed. The document then discusses PHP variables, operators, and gives a basic "Hello World" example.

Uploaded by

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

Web Programming Chapter 6 - PHP

PHP - INTRODUCTION

PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.

• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".


• PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
• It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
• PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on
the Unix side. The MySQL server, once started, executes even very complex queries with
huge result sets in record-setting time.
• PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4
added support for Java and distributed object architectures COMandCORBACOMandCORBA,
making n-tier development a possibility for the first time.
• PHP is forgiving: PHP language tries to be as forgiving as possible.
• PHP Syntax is C-Like.

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.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

• Simplicity
• Efficiency
• Security
• Flexibility
• Familiarity

"Hello World" Script in PHP

To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.

As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML orXHTMLifyou′recutting−edgeorXHTMLifyou′recutting−edge you'll have PHP statements like
this −

Live Demo

<html>

<head>
<title>Hello World</title>
</head>

<body>
<?php echo "Hello, World!";?>
</body>

</html>

It will produce following result −

Hello, World!

If you examine the HTML output of the above example, you'll notice that the PHP code is not
present in the file sent from the server to your Web browser. All of the PHP present in the Web
page is processed and stripped from the page; the only thing returned to the client from the Web
server is pure HTML output.

A most common tag is the <?php...?> and we will also use the same tag in our tutorial.
PHP - ENVIRONMENT SETUP

In order to develop and run PHP Web pages three vital components need to be installed on your
computer system.

• Web Server − PHP will work with virtually all Web Server software, including Microsoft's
Internet Information Server IISIIS but then most often used is freely available Apache Server.
Download Apache for free here − https://httpd.apache.org/download.cgi
• Database − PHP will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database. Download MySQL for free
here − https://www.mysql.com/downloads/
• PHP Parser − In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser. This tutorial will guide you
how to install PHP parser on your computer.

The main way to store information in the middle of a PHP program is by using a variable.

PHP - VARIABLE TYPES

Here are the most important things to know about variables in PHP.

• All variables in PHP are denoted with a leading dollar sign $$.
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance whether
it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when necessary.
• PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables −

• Integers − are whole numbers, without a decimal point, like 4195.


• Doubles − are floating-point numbers, like 3.14159 or 49.1.
• Booleans − have only two possible values either true or false.
• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters, like 'PHP supports string operations.'
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
• Resources − are special variables that hold references to resources external to
PHP suchasdatabaseconnectionssuchasdatabaseconnections.

Variable Naming

Rules for naming a variable is −

• Variable names must begin with a letter or underscore character.


• A variable name can consist of numbers, letters, underscores but you cannot use characters
like + , - , % , ,, . & , etc

There is no size limit for variables.

PHP - Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5
are called operands and + is called operator. PHP language supports following type of operators.

• Arithmetic Operators
• Comparison Operators
• Logical orRelationalorRelational Operators
• Assignment Operators
• Conditional orternaryorternary Operators

Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example


+ Adds two operands A + B will give
30

- Subtracts second operand from the first A - B will give -


10

* Multiply both operands A * B will give


200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer B % A will give 0


division

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Comparison Operators

There are following comparison operators supported by PHP language


Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

A==BA==Bis
== Checks if the value of two operands are equal or not, not true.
if yes then condition becomes true.

!= Checks if the value of two operands are equal or not, A!=BA!=B is


if values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the A>BA>B is not
value of right operand, if yes then condition becomes true.
true.

< Checks if the value of left operand is less than the A<BA<B is
value of right operand, if yes then condition becomes true.
true.

>= Checks if the value of left operand is greater than or A>=BA>=Bis


equal to the value of right operand, if yes then not true.
condition becomes true.

<= Checks if the value of left operand is less than or equal A<=BA<=Bis
to the value of right operand, if yes then condition true.
becomes true.

Logical Operators

There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −


Operator Description Example

AandBAandBis
and Called Logical AND operator. If both the operands true.
are true then condition becomes true.

or Called Logical OR Operator. If any of the two AorBAorB is true.


operands are non zero then condition becomes true.

&& Called Logical AND operator. If both the operands A && B A && Bis
are non zero then condition becomes true. true.

|| Called Logical OR Operator. If any of the two A||BA||B is true.


operands are non zero then condition becomes true.

! Called Logical NOT Operator. Use to reverses the ! A && B A && Bis
logical state of its operand. If a condition is true then false.
Logical NOT operator will make false.

Assignment Operators

There are following assignment operators supported by PHP language −

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values from C = A + B will assign


right side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right C += A is equivalent


operand to the left operand and assign the to C = C + A
result to left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent


right operand from the left operand and assign to C = C - A
the result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent


right operand with the left operand and assign to C = C * A
the result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the to C = C / A
result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent


modulus using two operands and assign the to C = C % A
result to left operand
Conditional Operator

There is one more operator called conditional operator. This first evaluates an expression for a true
or false value and then execute one of the two given statements depending upon the result of the
evaluation. The conditional operator has this syntax −

Show Examples

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise


Expression value Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

• Unary prefix operators, which precede a single operand.


• Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.
• The conditional operator aternaryoperatoraternaryoperator, which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the first
expression.
• Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left


Assignment = += -= *= /= %= Right to left

PHP - Decision Making


The if, elseif ...else and switch statements are used to take decision based on the different condition.

You can use conditional statements in your code to make your decisions. PHP supports following
three decision making statements −

• if...else statement − use this statement if you want to execute a set of code when a condition
is true and another if the condition is not true
• elseif statement − is used with the if...else statement to execute a set of code if one of the
several condition is true
• switch statement − is used if you want to select one of many blocks of code to be executed,
use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else
code.

The If...Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use
the if....else statement.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, Otherwise,
it will output "Have a nice day!":

Live Demo

<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

else
echo "Have a nice day!";
?>

</body>
</html>

It will produce the following result −

Have a nice weekend!

The ElseIf Statement

If you want to execute some code if one of the several conditions are true use the elseif statement

Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have
a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice day!" −

Live Demo

<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

elseif ($d == "Sun")


echo "Have a nice Sunday!";

else
echo "Have a nice day!";
?>

</body>
</html>

It will produce the following result −

Have a nice Weekend!

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax
switch (expression){
case label1:
code to be executed if expression = label1;
break;

case label2:
code to be executed if expression = label2;
break;
default:

code to be executed
if expression is different
from both label1 and label2;
}

Example

The switch statement works in an unusual way. First it evaluates given expression then seeks a
lable to match the resulting value. If a matching value is found then the code associated with the
matching label will be executed or if none of the lable matches then statement will execute any
specified default code.

Live Demo

<html>
<body>

<?php
$d = date("D");

switch ($d){
case "Mon":
echo "Today is Monday";
break;

case "Tue":
echo "Today is Tuesday";
break;

case "Wed":
echo "Today is Wednesday";
break;

case "Thu":
echo "Today is Thursday";
break;

case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;

case "Sun":
echo "Today is Sunday";
break;

default:
echo "Wonder which day is this ?";
}
?>

</body>
</html>

It will produce the following result −

Today is Monday

PHP - Loop Types


An array is a data structure that stores one or more similar type of values in a single value. For
example if you want to store 100 numbers then instead of defining 100 variables its easy to define
an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is
called array index.

• Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.
• Associative array − An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array function to create array. This function is explained in function reference.

Live Demo

<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −


Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.

NOTE − Don't keep associative array inside double quote while printing otherwise it would not
return any value.

Example
Live Demo

<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>

This will produce the following result −

Salary of mohammad is 2000


Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

You might also like