You are on page 1of 16

Unit 3

Introduction to PHP:
HP is a server scripting language, and a powerful tool for making dynamic
and interactive Web pages.

It a widely-used, free, and efficient alternative to competitors such as


Microsoft's ASP.

Incorporating PHP Within HTML-


PHP documents end with the extension .php. When a web server
encounters this extension in a requested file, it automatically passes it to
the PHP processor. web servers are highly configurable, and some web
developers choose to force files ending with .htm or .html to also get
parsed by the PHP processor.

At its very simplest, a PHP document will output only HTML. To prove
this, you can take any normal HTML document, such as an index.html file,
and save it as index.php; it will display identically to the original.

Calling the PHP Parser


A small PHP “Hello World” program might look like example below.

<?php
echo "Hello world";
?>

Structure of PHP
A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".


Variables
Variables are "containers" for storing information

Creating (Declaring) PHP Variables


In PHP, a variable starts with the $ sign, followed by the name of the
variable:

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

operator in php:

PHP language supports following type of operators.

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

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 division B % A will give 0

++ 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

== Checks if the value of two operands are equal or not, if yes then (A == B) is not
condition becomes true. true.

!= Checks if the value of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.

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

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

>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand, if yes then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true. true.
Logical Operators
There are following logical operators supported by PHP language

Operator Description Example

and Called Logical AND operator. If both the operands are true then (A and B) is
condition becomes true. true.

or Called Logical OR Operator. If any of the two operands are non zero (A or B) is
then condition becomes true. true.

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

|| Called Logical OR Operator. If any of the two operands are non zero (A || B) is
then condition becomes true. true.

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

Assignment Operators
There are following assignment operators supported by PHP language −

Operator Description Example

= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand value of A + B into C

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


left operand and assign the result to left operand C=C+A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C
operand from the left operand and assign the result to left =C-A
operand

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


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

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


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

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


two operands and assign the result to left operand C=C%A

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

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X : Otherwise 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 (a ternary operator), 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 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.

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 echo and print Statements


echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.

The echo statement can be used with or without parentheses: echo or echo().

Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):

Example
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

The print statement can be used with or without


parentheses: print or print().

Display Text

The following example shows how to output text with the print command
(notice that the text can contain HTML markup):

Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

PHP functions: A function is a piece of code which takes one more input in the form
of parameter and does some processing and returns a value.
There are two parts which should be clear to you −

• Creating a PHP Function


• Calling a PHP Function

Creating PHP Function


Its very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call
it. Following example creates a function called writeMessage() and then calls it just
after creating it.
<html>

<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice
time!";
}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>

This will display following result −


You are really a nice person, Have a nice time!

PHP Functions with Parameters


PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function.
<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>

This will display following result −


Sum of the two numbers is : 30

PHP Functions returning value


A function can return a value using the return statement in conjunction with a value
or object. return stops the execution of the function and sends the value back to the
calling code.
We can return more than one value from a function using return array(1,2,3,4).
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

This will display following result −


Returned value from the function : 30

Dynamic Function Calls


It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself. Following example depicts
this behaviour.
Live Demo

<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

</body>
</html>

This will display following result −


Hello

PHP Variables Scope


In PHP, the scope of a variable is the part of the script where the variable
can be referenced/used.

PHP has three different variable scopes:

• local
• global
• static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

Example
Variable with global scope:

<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
Variable with local scope:

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

The static Keyword


Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted.

To do this, use the static keyword when you first declare the variable:

Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

Expressions and control flow in PHP:


Expressions

An expression is a combination of values, variables, operators, and


functions that results in a value. It’s familiar to anyone who has taken
high-school algebra:
y = 3(abs(2x) + 4)

which in PHP would be:

$y = 3 * (abs(2 * $x) + 4);

The value returned (y, or $y in this case) can be a number, a string,


or a Boolean value

TRUE or FALSE?

A basic Boolean value can be either TRUE or FALSE. For example, the
expression “20 > 9” (20 is greater than 9) is TRUE, and the expression “5
== 6” (5 is equal to 6) is FALSE

Flow-Control Statements

PHP supports a number of traditional programming constructs for


controlling the flow of execution of a program.

Conditional statements, such as if/else and switch, allow a program to


execute different pieces of code, or none at all, depending on some
condition. Loops, such as while and for, support the repeated execution
of particular code.

if
The if statement checks the truthfulness of an expression and, if the
expression is true, evaluates a statement. An if statement looks like:

if (expression)
statement
To specify an alternative statement to execute when the expression is false,
use the else keyword:

if (expression)
statement
else
statement

For example:

if ($user_validated)

echo "Welcome!";

else

echo "Access Forbidden!";

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

Operator Description Example

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


Expression Y

Try following example to understand the conditional operator.


<html>

<head>
<title>Arithmetical Operators</title>
</head>

<body>
<?php
$a = 10;
$b = 20;

/* If condition is true then assign a to result


otheriwse b */
$result = ($a > $b ) ? $a :$b;

echo "TEST1 : Value of result is $result<br/>";

/* If condition is true then assign a to result


otheriwse b */
$result = ($a < $b ) ? $a :$b;

echo "TEST2 : Value of result is $result<br/>";


?>

</body>
</html>

This will produce the following result −


TEST1 : Value of result is 20
TEST2 : Value of result is 10

Break, continue in PHP:

Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

Include and Require Files in php:


If we can include files using the include() statement then why we
need require(). Typically the require() statement operates
like include().

— the include() statement will only generate a PHP warning but allow
script execution to continue if the file to be included can't be found, whereas

---the require() statement will generate a fatal error and stops the script
execution.

Syntax
include 'filename';

or

require 'filename';
EXAMPLE:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

You might also like