Advanced Internet Programming
ITec3091
2
Chapter 2
PHP Basics
3 Variables
The main way to store information in the middle of a PHP program is by using a variable. 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.
PHP does a good job of automatically converting types from one to another when necessary.
4 Variable naming rule and data types
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.
Data Types: Php supports the following data types.
Integer: are whole numbers without decimal point. Example: 10,6,76.
Double: are floating points. Example: 2.5, 3.99, 0.5.
String: is a sequence of characters. Example: “Information Technology”.
NULL: a special type only have one value NULL.
Array: named and indexed collection of other values. Example: $num=array(1,2,3,4,5);
Object: instance of programmer defined classes.
Resources: special variable that holds a reference to resources external to the PHP. Example: Database
connection
Boolean: have only two positive values either true or false.
5 PHP – Scope of Variables
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP
variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
6
PHP Local Variables
A variable declared in a function is considered local; that is, it can be referenced solely in that function.
Any assignment outside of that function will be considered to be an entirely different variable from the one contained
in the function:
<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. <br> ";
}
assignx();
print "\$x outside of function is $x. ";
?>
This will produce the following result.
$x inside function is 0.
$x outside of function is 4.
7 PHP Function Parameters
PHP Functions are covered in detail in PHP Function Chapter.
In short, a function is a small unit of program which can take some input in the form of parameters and does some
processing and may return a value.
Function parameters are declared after the function name and inside parentheses. They are declared much like a typical
variable would be:
<?php
// multiply a value by 10 and return it to the caller
function multiply ($value)
{
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval<br>";
?>
This will produce the following result.
Return value is 100
8 PHP Global Variables
In contrast to local variables, a global variable can be accessed in any part of the program.
However, in order to be modified, a global variable must be explicitly declared to be global in the function
in which it is to be modified.
by placing the keyword GLOBAL in front of the variable that should be recognized as global.
<?php
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result.
Somevar is 16
9 PHP Static Variables
In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static
variable will not lose its value when the function exits and will still hold that value should the function be called
again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result.
1 2 3
10 PHP ─ Constants
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.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to
simply specifying its name.
Unlike with variables, you do not need to have a constant with a $. You can also use the function
constant() to read a constant's value if you wish to obtain the constant's name dynamically.
11 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 "<br>";
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (Boolean, integer, float and string) can be contained in
constants.
12 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.
13 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 (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Let’s have a look on all operators one by one
14 Arithmetic Operators
The following arithmetic operators are supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
15 Comparison Operators
There are following comparison operators supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then:
Logical Operators
16
The following logical operators are supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then:
Assignment Operators
17
PHP supports the following assignment operators:
Conditional Operator
18
There is one more operator called the conditional operator. It first evaluates an expression for a true or
false value and then executes one of the two given statements depending upon the result of the evaluation.
Cont…
19
Try the 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 otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $x:$y;
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
20 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 the
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 several
condition are 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.
21 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;
22 Example
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
The above example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
23 The ElseIf Statement
If you want to execute some code if one of the several conditions is true, then 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;
24 example
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Wen")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
The above 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!":
25
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.
The switch statement works in an unusual way. First it evaluates the given expression, then seeks a label to match the resulting
value. If a matching value is found, then the code associated with the matching label will be executed. If none of the labels
match, then the statement will execute any specified default 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
26 <?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 ?";
?>
27
PHP ─ Loop Types
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.
28 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.
29 Example
The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop:
<?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" );
?>
This will produce the following result:
At the end of the loop a=50 and b=25
30 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;
}
31
Example
This example decrements a variable value on each iteration of the loop and the counter increments until it
reaches 10 when the evaluation becomes false and the loop ends.
<?php
$i = 5;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
This will produce the following result:
Loop stopped at i = 10and num = 40
32 The do...while loop statement
The do...while statement will execute a block of code at least once - it will then
repeat the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
33 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:
<?php
$i = 0;
$num = 0;
do
{
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
This will produce the following result:
Loop stopped at i = 10
34 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;
}
35 Example
Try out the following example to list out the values of an array.
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
This will produce the following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
36 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. If 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.
In the following example, the condition test becomes true when the counter value
reaches 3 and loop terminates.
37 Con’t
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
This will produce the following result:
Loop stopped at i = 3
38 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.
In the following example, the loop prints the value of array, but when the condition becomes
true, it just skips the code and next value is printed.
39 Con’t
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
This will produce the following result:
Value is 1
Value is 2
Value is 4
Value is 5
40 PHP ─ Arrays
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, it is easy to
define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID 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
41
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers. By default, the array index starts from zero.
The following example demonstrates how to create and access numeric arry.
<?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 />";
}
?>
42 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
43 <?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 />";
?>
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
44 array, and so on. Values in the multi-dimensional array are accessed using multiple index.
<?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 />";
?>
45 PHP ─ Strings
They are sequences of characters.
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values.
Example:
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
$literally = "My $variable will print!";
print($literally);
?>
This will produce the following result:
My $variable will not print!
My name will print
46 Cont…
There are no artificial limits on string length - within the bounds of available memory, you ought to be
able to make arbitrarily long strings.
Strings that are delimited by double quotes (“ “) are preprocessed in both the following two ways by
PHP:
Certain character sequences beginning with backslash (\) are replaced with special characters
Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
47 String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce the following result:
Hello World 1234
48 Using the strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce the following result:
12
49 Using the strpos() function
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is
found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
This will produce the following result:
6
50 PHP ─ Functions
PHP functions are similar to other programming languages.
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.
A) User defined function
There are two parts which should be clear to you:
Creating a PHP Function
Calling a PHP Function
51 Creating PHP Function
It is 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.
The following example creates a function called WriteMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should
be put inside { and } braces as shown in the following example below:
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
52 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.
The following example takes two integer parameters and adds them together and then prints them.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
53 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.
You can return more than one value from a function using return array(1,2,3,4).
The following example takes two integer parameters and add them together and then returns their sum to the
calling program. Note that return keyword is used to return a value from a function.
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
54 Setting Default Values for Function
Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it.
The following function prints NULL in case you does not pass any value to this function.
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
55 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.
The following example depicts this behavior.
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
56 B) PHP Built in Functions
PHP Built in Functions: the real power of PHP comes from function. There are above 700
functions Available. Example:
phpinfo() function: Used to output the PHP information and troubleshooting and to provide
version of PHP and how it is configured.
Php header() function: Used to send row HTTP headers over HTTP protocol. This
function must be called before anything is written to the page.
PHP date() function: used to format time and date. Example:
<?php
echo date(“y/m/d”);//returns current date
?>