PHP
Server side scripting vs. Client side scripting
1. Server side scripting is used to create dynamic 1. Client side scripting is used when the
pages based a number of conditions when the users browser already has all the code and
users browser makes a request to the server. the page is altered on the basis of the
users input.
2. The Web Server executes the server side 2.
scripting that produces the page to be sent to The Web Browser executes the client side
the browser. scripting that resides at the user’s
computer.
3. Server executes server-side scripts to send out
a page but it does not execute client-side 3. The browser receives the page sent by the
scripts. server and executes the client-side scripts.
4.
4. Server side scripting is used to connect to the Client side scripting cannot be used to
databases that reside on the web server. connect to the databases on the web
server.
5. Server side scripting can access the file system
residing at the web server. 5. Client side scripting can’t access the file
system that resides at the web server.
6. Server side scripting can’t be blocked by the 6. Client side scripting is possible to be
user. blocked by the user.
7.
7. Response from a server-side script is slower as Response from a client-side script is faster
compared to a client-side script because the as compared to a server-side script
scripts are processed on the remote because the scripts are processed on the
computer. local computer.
8. Examples of Client side scripting
8. Examples of Server side scripting languages : languages : Javascript, VB script, etc.
PHP, JSP, ASP, [Link], Ruby, Perl n many
more.
FEATURES OF PHP
The main features of php is; it is open source scripting language so you can free
download this and use. PHP is a server site scripting language. It is open source scripting
language. It is widely used all over the world. It is faster than other scripting language.
Some important features of php are given below;
Features of php
It is most popular and frequently used world wide scripting language, the main reason of
popularity is; It is open source and very simple.
• Simple
• Faster
• Interpreted
• Open Source
• Case Sensitive
• Simplicity
• Efficiency
• Platform Independent
• Security
• Flexibility
• Familiarity
Simple
It is very simple and easy to use, compare to other scripting language it is very simple
and easy, this is widely used all over the world.
Interpreted
It is an interpreted language, i.e. there is no need for compilation.
Faster
It is faster than other scripting language e.g. asp and jsp.
Open Source
Open source means you no need to pay for use php, you can free download and use.
Platform Independent
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.
Case Sensitive
PHP is case sensitive scripting language at time of variable declaration. In PHP, all
keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are NOT case-sensitive.
Variable in PHP
Variable is an identifier which holds data or another one variable and whose value can
be changed at the execution time of script. In PHP, a variable starts with the $ sign,
followed by the name of the variable.
Syntax
$variablename=value;
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
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
<?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
<?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>";
?>
PHP 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. We need it for a further
job.
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();
?>
Constant
A constant is a name or an identifier for a simple value. A constant value cannot change
during the execution of the script. By default, a constant is case-sensitive. By
convention, constant identifiers are always uppercase. A constant name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. If you
have defined a constant, it can never be changed or undefined.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It
is stored in a variable or returned by a function.
constant() example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Differences between constants and variables are
• There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
• Constants may be defined and accessed anywhere without regard to variable scoping
rules.
• Once the Constants have been set, may not be redefined or undefined.
PHP Data Types
Variables can store data of different types, and different data types can do different
things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed
with 0x) or octal (8-based - prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result Show it
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced in PHP 5.6)
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the assignment expression on the right.
Assignment Same as... Description Show it
The left operand gets set to the value of the expression
x=y x=y
on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result Show it
== Equal $x == $y Returns true if $x is equal to $y
$x ===
=== Identical Returns true if $x is equal to $y, and they are of the same type
$y
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
Returns true if $x is not equal to $y, or they are not of the same
!== Not identical $x !== $y
type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
Greater than or equal
>= $x >= $y Returns true if $x is greater than or equal to $y
to
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP 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.
Operator Name Description Show it
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result Show it
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
• if statement - executes some code if one condition is true
• if...else statement - executes some code if a condition is true and another code if that
condition is false
• if...elseif....else statement - executes different codes for more than two conditions
• switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if....else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement
The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
Example
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
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
<?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!";
}
?>
Loop
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
• for − loops through a block of code a specified number of times.
• while − loops through a block of code if and as long as a specified condition is true.
• do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.
• foreach − loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.
The for loop statement
The for statement is used when you know how many times you want to execute a statement or a
block of statements.
Syntax
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on
each pass of the loop −
Live Demo
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
This will produce the following result −
At the end of the loop a = 50 and b = 25
The while loop statement
The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the
test expression will again be evaluated and the loop will continue until the test expression is
found to be false.
Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
Live Demo
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10) {
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 10 and num = 40
The do...while loop statement
The do...while statement will execute a block of code at least once - it then will repeat the loop as
long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
Live Demo
<html>
<body>
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 10
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next
element will be processed.
Syntax
foreach (array as value) {
code to be executed;
}
Example
Try out following example to list out the values of an array.
Live Demo
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array 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
Jumping Statements
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. It gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop
terminates.
Live Demo
<html>
<body>
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce the following result −
Loop stopped at i = 3
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate
the loop.
Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it
just skip the code and next value is printed.
Live Demo
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value ) {
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 4
Value is 5
Array
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
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects −
This example is an associative array, you can create numeric array in the same fashion.
Live Demo
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce the following result −
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39