Module 4 PHP
Module 4 PHP
MODULE 4
INTRODUCTION
Arrays in PHP are a type of data structure that allows storing multiple elements
under a single variable. An array in PHP is actually an ordered. A map is a type
that associates values to keys. The array elements can be accessed using their
index or key (array index).
CREATING AN ARRAY
<?php
$color[0] = "Red";
$color[1] = "Green";
$color[2] = "Blue";
?>
Here array is created through array construct. The array() takes a comma
separated list of elements to be stored
<?php
?>
PHP MODULE 4 S.A
$arr = array();
Or arrays can be created using the special syntax mentioning the key
value pair.
Here keys and values are separated using special symbol =>.
The final way to create an array in a script is to call a function that returns
an array.
TYPES OF ARRAYS
There are three different kinds of arrays and each array value is accessed using
an ID which is called array index.
An indexed or numeric array stores each array element with a numeric index.
Syntax:
Example
<?php
?>
or
<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>
Associative Arrays
Example
<?php
?>
PHP MODULE 4 S.A
Or it can be written as
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>
Multidimensional Arrays
PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep.
print $arr[0][1];
Syntax:
... );
Example:
<?php
$myarray = array(
array("Ankit", "Ram", "Shyam"),
array(“Tcr", "Trichy", "Kanpur")
);
PHP MODULE 4 S.A
The structure and values of any array can be viewed by using one of two
statements — var_dump() or print_r(). The print_r() statement, however,
gives somewhat less information. The var_dump() function is used to dump
information about a variable. This function displays structured information such
as type and value of the given variable.
unset() Function: The unset() function is used to remove element from the
array. The unset function is used to destroy any other variable and to delete any
element of an array
<?php
$arr = array('G', 'E', 'E', 'K', 'S');
// Display the array element
print_r($arr);
unset($arr[2]);
print_r($arr);
?>
Output
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
array_change_key_case() - The function changes all keys in an array to
lowercase or uppercase.
Example:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_UPPER));
?>
Output
Example
<?php
print_r(array_chunk($input, 2));
?>
In this example the given array is divided into chunks of 2.
Output
Array
(
[0] => Array
(
[0] => abc
[1] => bcd
) [1] =>
Array(
[0] => cde
[1] => def ))
PHP MODULE 4 S.A
Syntax
array_combine(keys, values);
Example
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
Output
Syntax
array_count_values(array);
Example
<?php
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
?>
PHP MODULE 4 S.A
Output
array_diff() – The function compares the values of two (or more) arrays, and
returns the differences. This function compares the values of two (or more)
arrays, and returns an array that contains the entries from array1 that are not
present in array2 or array3, etc.
Example
<?php
$result=array_diff($a1,$a2);
print_r($result);
?>
Output
Parameter Description
value Required. Specifies the value to use for filling the array
PHP MODULE 4 S.A
<?php
$a1=array_fill(3,4,"blue");
$b1=array_fill(0,1,"red");
print_r($a1);
echo "<br>";
print_r($b1);
?>
Output
Array ( [3] => blue [4] => blue [5] => blue [6] => blue )
Syntax
array_flip(array);
Example
<?php
$a1=array("a"=>"red","b"=>"green");
$result=array_flip($a1);
print_r($result);
?>
Output
Array ( [red] => a [green] => b
PHP MODULE 4 S.A
Example
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_intersect($a1,$a2);
print_r($result);
?>
Output
Array ( [a] => red [b] => green [c] => blue )
Syntax
array_key_exists(key, array);
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
Output
Array ( [0] => Volvo [1] => BMW [2] => Toyota )
PHP MODULE 4 S.A
array_merge() - The function merges one or more arrays into one array.
Syntax
Example
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Syntax
array_pop(array);
Example
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output
Syntax
array_product(array);
Example
<?php
$a=array(5,5);
echo(array_product($a));
?>
Output
25
Syntax
Example
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Output
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
PHP MODULE 4 S.A
Syntax
array_reverse(array);
Example
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
array_replace() - The function replaces the values of the first array with the
values from following arrays.
Syntax
Example
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
Output
Array ( [0] => blue [1] => yellow )
PHP MODULE 4 S.A
array_search() -The function search an array for a value and returns the key
of the found value.
Example
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Output
The length parameter is optional and it specifies the length of the returned array.
Here in the example it starts the slice from the third array element(index 2), and
return the rest of the elements in the array:
Example
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Output
Array ( [0] => blue [1] => yellow [2] => brown )
PHP MODULE 4 S.A
Syntax
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Output
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
array_sum() - The function returns the sum of all the values in the array.
Syntax
array_sum(array);
Example
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
Output
45
array_unique() – The function removes duplicate values from an array. If
two or more array values are the same, the first appearance will be kept and the
other will be removed.
PHP MODULE 4 S.A
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
Output
Syntax
array_values(array);
Example
<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>
Output
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output
3
PHP MODULE 4 S.A
shuffle() – The function randomizes the order of the elements in the array.
Example
<?php
$my_array=array("red","green","blue","yellow","purple");
shuffle($my_array);
print_r($my_array);
?>
Output
Array ( [0] => yellow [1] => purple [2] => red [3] => blue [4] => green )
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
Output
BMW
Toyota
Volvo
PHP MODULE 4 S.A
Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Output
Volvo
Toyota
BMW
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
print_r($age);
Output
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
print_r($age)
?>
Output
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
print_r($age)
?>
Output
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
print_r($age)
?>
Output
<?php
$number=range(0,5);
print_r($number);
?>
Output
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )
PHP provides several ways to traverse arrays using both array iteration
functions and language constructs: foreach, list/each, for loops etc.
PHP MODULE 4 S.A
foreach Loop:
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array. It loops through a block of code for each element in
an array.
Syntax
{
code to be executed;
}
or
In the first example, for every loop iteration, the value of the current array
element is assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
PHP MODULE 4 S.A
The following example will output both the keys and the values of the given
array ($age):
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val)
{
echo "$x = $val<br>";
}
?>
Output
Peter = 35
Ben = 37
Joe = 43
list() function
The list() function is used to assign values to a list of variables in one operation.
This is a language construct. The first element in the given array is assigned to
the first variable passed and the second element to the second variable and so
on,
Syntax:
Example
<?php
$my_array = array("php","java","python");
list($a, $b, $c) = $my_array;
PHP MODULE 4 S.A
Output:
STRING IN PHP
<?php
?>
If strings are enclosed in single quotation almost no processing is done. All the
escape sequences like \t or \n, will be printed as specified instead of having
any special meaning. If it is enclosed in double quotes PHP will merge the
values of any variable we include. It interprets the Escape sequences. Each
variable will be replaced by its value.
$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.
A string can also be specified using heredoc statement. It is used for specifying
large chunk of statements. The operator in heredoc statement is <<< operator.
<?php
$str = <<<demo
PHP MODULE 4 S.A
PHP provides various string functions to access and manipulate strings. The
PHP string functions are part of the PHP. No external installation is required to
use these functions.
The PHP strlen() function returns the length of a string including white spaces.
If the string is empty the function will return 0.
syntax
strlen(string);
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
strpos() – The function finds the position of the first occurrence of a string
inside another string.
Syntax
Parameter Values
Parameter Description
Example
<?php
echo strpos("I like php I like php too!","php");
?>
Output
strrpos() – The function finds the position of the last occurrence of a string
inside another string.
PHP MODULE 4 S.A
Syntax
strrpos(string,find,start);
Example
<?php
?>
Output
19
stripos() – The function finds the position of the first occurrence of a string
inside another string.
<?php
echo stripos("I love php, I love php too!","PHP");
?>
Output
7
strripos() –The function finds the position of the last occurrence of a string
inside another string.
PHP MODULE 4 S.A
<?php
?>
Output
19
strstr() – The function searches for the first occurrence of a string inside
another string. Returns the rest of the string (from the matching point) to the end
of the string.
strstr(string,search);
<?php
?>
Output
world!
stristr() –The function searches for the first occurrence of a string inside
another string.
<?php
?>
Output
world!
Syntax
substr(string,start,length);
Parameter Values
Parameter Description
<?php
?>
Output
world
Parameter Description
strcmp(string1,string2);
Example
<?php
?>
PHP MODULE 4 S.A
Output
Example 2
<?php
$str1 = "PHP";
$str2 = "PYTHON";
?>
Output
-3
3
0
<?php
?>
Output
0
PHP MODULE 4 S.A
Example
<?php
?>
Output
Hi World!
Syntax -
strrev(string);
Example
<?php
Output
!dlroW olleH
<?php
echo strtolower($str);
?>
Output
welcome to php
Example
<?php
echo strtoupper($str);
?>
Output
WELCOME TO PHP
<?php
?>
Output
Hello world!
Example
<?php
?>
ucwords() – The function converts the first character of each word in a string
to uppercase.
Example
<?php
?>
Output
Hello World
str_word_count( str);
Example
<?php
?>
Output
Related functions:
Note: The echo() is not actually a function, so you are not required to use
parentheses with it.
Variable values can be passed between pages through the URL (in address bar
of the browser). Here values are visible to the user and others as they appear in
PHP MODULE 4 S.A
the address bar and also in the browser history. This is not a secure way to
transfer sensitive data like password, etc.
HTTP is a stateless protocol and thus values between page requests cannot be
preserved. So cookies or sessions are used to store the variables while
passing values between pages.
Cookies are stored at the client end and values can be passed between pages
using PHP. But here the client browser can reject accepting cookies by
changing the security settings of the browser. So this system can fail to pass
values between pages if user or client end settings are changed. But cookies are
quite useful in handling user entered values and passing them between pages.
Sessions are stored at the server end. This is one of the secured ways in which
the variables are passed between pages. Session variables hold information
about one single user, and are available to all pages in one application. The best
example of such a system is when we see our user-id after we log in. In
a member login system the user details are verified and once found correct, a
new session is created and with user id of the member and this value is stored at
server end. Every time a new page is opened by the browser, the server checks
the associated session value and display the user id. This system is more secure
and the member doesn't get any chance to change the values.
PHP MODULE 4 S.A
There are different ways by which values of variables can be passed between
pages. One of the ways is to use the URL to pass the values or data. Here one
main concern is that the data gets exposed in address bar of the browser and can
be easily accessible by using browser history. So it is not a good idea to pass
sensitive data like password through the URL to different pages or different
sites.
There are two ways the browser client can send information to the web server.
The GET method passes arguments from one page to the next as part of the
URL query string. When used for form handling, GET appends the indicated
variable name and value to the URL in the action attribute with a question
mark separator and submits the whole thing to the Web server.
In this scheme, name/value pairs are joined with equal signs and different pairs
are separated by the ampersand.
example_form.php?name1=value1&name2=value2
Spaces are removed and replaced with the + character and any other non-
alphanumeric characters are replaced with a hexadecimal values. Before the
browser sends the information, it encodes it using a scheme called URL
encoding. After the information is encoded it is sent to the server. The server
will decode the special characters automatically.
PHP MODULE 4 S.A
<html>
<body>
<form action="registration.php" method="GET">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
</body>
</html>
The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP you can make sure
that your information is secure.
The PHP provides $_POST associative array to access all the sent
information using POST method.
coder.php
<?php
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
}
?>
PHP MODULE 4 S.A
<html>
<body>
</body>
</html>
The following table compares the two HTTP methods: GET and POST.
GET POST
Cookies are text files stored on the client computer and they are kept for
tracking purpose. PHP transparently supports HTTP cookies. It is a piece of
data used to store variables name, value along with information on the site from
which it came from and an expiration time.
Server script sends a set of cookies to the browser. For example name,
age, or identification number etc.
When next time browser sends any request to web server then it sends
those cookies information to the server and server uses that information
to identify the user.
PHP MODULE 4 S.A
A cookie can be used for authentication, storing site preferences, shopping cart
contents etc. A cookie consists of one or more name value pairs. Websites can
modify their own cookies.
Cookies are sent as a field in header of HTTP response by web server to web
browser.
Example
$value = “anyvalue”;
setcookie("Test", $value, time()+3600, "/~rasmus/", "example.com", 1,1);
Note: Only the name parameter is required. All other parameters are optional.
Value − This sets the value of the named variable and is the content that
you actually want to store.
Path − This specifies the directories for which the cookie is valid
Domain − This can be used to specify the domain name. All cookies are
only valid for the host and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be
sent by secure transmission using HTTPS otherwise set to 0 which mean
cookie can be sent by regular HTTP.
The value of the cookie can be retrieved using the global variable $_COOKIE.
The isset()function is used to find out if the cookie is set:.
<?php
$cookie_name = "user";
?>
<html>
<body>
<?php
if(isset($_COOKIE[$cookie_name]))
}
else
PHP MODULE 4 S.A
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:
Example
<?php
?>
<html>
<body>
<?php
?>
</body>
</html>
PHP MODULE 4 S.A
The following example creates a small script that checks whether cookies are
enabled. First create a test cookie with the setcookie() function, then count the
$_COOKIE array variable:
<?php
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0)
} else {
?>
</body>
</html>
PHP MODULE 4 S.A
Also every time the browser requests a URL to the server, all the cookie data for
a website is automatically sent to the server within the request. It means if you
have stored 5 cookies on user's system, each having 4KB in size, the browser
needs to upload 20KB of data each time the user views a page, which can affect
your site's performance.
PHP session can be used to solve the above problem. A PHP session stores data
on the server computer. In a session based environment, every user is identified
through a unique number called session identifier or SID.
By default, session variables last until the user closes the browser
Here data is kept in the server and a “key” (SID) is given to the client to
uniquely identify themselves.
The PHP code in the example below simply starts a new session.
<?php
// Starting session
session_start();
?>
PHP MODULE 4 S.A
All session data are stored as key-value pairs in the $_SESSION[] super global
array. The stored data can be accessed during the lifetime of a session.
<?php
// Starting session
session_start();
Destroying a Session
If you want to remove certain session data, simply unset the corresponding key
of the $_SESSION associative array, as shown in the following example:
<?php
// Starting session
PHP MODULE 4 S.A
session_start();
<?php
// Starting session
session_start();
// Destroying session
session_destroy();
?>
Most sessions set a user-key on the user's computer that looks something like
this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
another page, it scans the computer for a user-key. If there is a match, it
accesses that session, if not, it starts a new session. The browser can send
session ID to server through cookie or as URL parameter. The length of the
session is determined by session timeout setting in php.ini file. The default is
24 minutes.
PHP MODULE 4 S.A
Cookie Session
Cookies end on the expiry time set by When the user quits the browser or logs out of the
the user. programmed, the session is over.
Cookies are not secured. Session are more secured compare than cookies.
Cookies stored data in text file. Session save data in encrypted form.
HTTP HEADERS
General: These headers are used by both client and servers. It contains general
information such as, Cache-control, Date, Connection etc.
Entity: This header fields contains the format of the content being sent by
server and client. Headers like Content-Length, Content-Language, Content-
Encoding are entities headers.
PHP MODULE 4 S.A
The header() function is used to send raw http headers. The header() are those
functions which manipulate information sent to the client or browser by the Web
server, before any other output has been sent.
<?php
header("HTTP/1.0 404 Not Found");
?>
Uses
o It changes the page location.
o It sets the time zone.
o This function sets the caching control.
o It initiates the force download.
The following code will redirect your user to some another page.
<?php
// This will redirect the user to the new location
header('Location: http://www.tester.com/');
<?php
header( "refresh:10;url=example.php");
echo 'You will be redirected in 10 seconds. If not please
click<ahref="example.php">here</a>.';
?>
By using the following code, you can prevent the browser to cache pages.
<?php
// PHP program to describes header function
<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
Header() is used to prompt the user to save a generated PDF file (Content-
Disposition header is used to supply a recommended filename and force the
browser to display the save dialog box):
The header() can also be used for purposes like HTTP authentication, sending
specific errors to browse