0% found this document useful (0 votes)
7 views13 pages

lec12 PHPP

This document provides an introduction to PHP, covering operators, conditional statements, looping statements, and arrays. It explains various PHP operators, including arithmetic, assignment, string, logical, equality, and comparison operators, as well as how to use conditional statements like if, if-else, and switch. Additionally, it discusses how to handle forms and pass data between pages using super global variables $_GET and $_POST, along with an overview of sessions.

Uploaded by

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

lec12 PHPP

This document provides an introduction to PHP, covering operators, conditional statements, looping statements, and arrays. It explains various PHP operators, including arithmetic, assignment, string, logical, equality, and comparison operators, as well as how to use conditional statements like if, if-else, and switch. Additionally, it discusses how to handle forms and pass data between pages using super global variables $_GET and $_POST, along with an overview of sessions.

Uploaded by

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

Introduction to PHP…

In the previous lecture we stated the PHP. We discussed the basics rules of PHP, embedding
PHP in HTML, and use of constants and variables in PHP. In this lecture we will continue the
introduction of PHP and will learn about operators in PHP, conditional statements in PHP,
looping statements in PHP and arrays in PHP.
1. PHP operators:
An operator is a symbol used to perform a specific operation on variables or operands. PHP
provides several types of operators to represent different operations. Following are the
operators available in PHP
Arithmetic operators: arithmetic operators are used to represent arithmetic operations. PHP
uses the following arithmetic operators
 + operator is used to perform addition operation
 -operator is used to perform subtraction operation
 / operator is used to perform division operation
 *operator is used to perform multiplication operation
 % operator is used to find remainder
Assignment operator: is used to assign a value to a variable. PHP uses the following assignment
operators
 = is used to assign a value to a variable
 +=operator adds and assigns a value. For example $a += $b, here += adds the value of $b
in $a and then assigns the result to $a. -=, *= and/= operators can also be used
 .= operator concatenates and assign the value. For example $.=$b, here .= concatenates
the value of $b with $a and then assigns this value to $a
Following example shows the use of assignment operators. First we use = operator to assign
values to $a and $b. Then we applied += and .= operators on these variables.
<html>
<head>
<title>Using operators</title>
</head>
<body>
<?php
$a=10;
$b=10.5;
echo $a+=$b;
echo "<br>";
echo $a.=$b;
?>
</body>
</html>

The output of the above program is given below

String operators: these operators are used to perform an operation on strings. PHP provides
the following string operators
 . operator is used to concatenate two strings
 .= operator concatenates and assign the value. For example $.=$b, here .= concatenates
the value of $b with $a and then assigns this value to $a
Increment and decrement operators: increment operator is used to increase the value of a
variable by 1 while decrement operator is used to decrease the value of a variable by 1. In PHP
++ operator is used as an increment operator and – operator is used as decrement operator.
These operators can be used in two forms; postfix and prefix. ++$a is an example of prefix
increment operator while $a++ is an example of postfix increment operator. When we use an
increment operator in prefix form, it adds 1 in the value of a variable and then use the new
value while in postfix form first the value of the variable is used and then incremented.
Logical operators: are used to perform logical operations on variables. In PHP, AND or &&
operators represent logical and operation, OR or || represent logical or operation, Not or !
represent logical not operation and XOR represents logical exclusive-or operation.
Equality operators: these operators are used to check the equality or inequality of variables. ==
operator checks the equality of two operands. It only checks the value while the type of
variable is not checked. === operator is used to check both types and values of variables. !=
operator is used to check inequality of variables.
Comparison operators: these operators are used to compare the values of two variables. >, <,
>= and <= are basic comparison operators.
2. Conditional statements:
Conditional statements make it possible for your computer program to respond accordingly toa
wide variety of inputs, using logic to discern between various conditions based on input value.
In PHP following conditional statements are available.
If statement:if statements allow code to be executed when the condition specified is met; if the
condition is true thenthe code in the curly braces is executed. Here is the syntax for an if
statement:
if (condition)
{ statement }
if….else statement:When you have two possible situations and you want to react differently for
each, you can use an if...else statement. This means: “If the conditions specified are met, run
the first block of code; otherwiserun the second block.” The syntax is as follows:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Switch statement:You can think of the switch statement as a variant of the if-else combination,
often used when youneed to compare a variable against a limited number of values called cases
in switch statement terminology. The syntax of the switch statement in PHP is
switch(variable)
{
case option:
action
break;
.
.
}

The following example shows the use of conditional statement. We declared a variable and
finds that is it even or odd?
<html>
<head>
<title>Switch </title>
</head>
<body>
<?php
$num=12;
$opt=$num%2;
switch($opt)
{
case 0:
echo "Even";
break;
case 1:
echo "Odd";
}
?>
</body>
</html>

3. Looping statements in PHP:


Looping statements are used to execute the same block of code a specified number of times.
Following are the basic loops in PHP.
 A while loop runs the same block of code while or until a condition is true. Syntax of for
loop is given below
while loop
while(condition)
{
Statements
Increment/decrement
}
 A do while loop runs once before the condition is checked. If the condition is true, it will
continue to run until the condition is false. (The difference between a do and a do while
loop is that do while runs once whether or not the condition is met.).
do
{
Statements
Increment/decrement
}
While (condition)
 A for loop runs the same block of code a specified number of times (for example, five
times).
for($a=0; $a<10; $a++)
{
statements
}
 A foreach loop is used to read an array.
In the following example we used the foreach loop to read an entire array.
<html>
<head>
<title>Foreach loop</title>
</head>
<body>
<?php
$players=array('yousuf'=>"M. Yousuf",'younus'=>'Younus Khan');
echo $players['yousuf']."<br>";
echo $players['younus'];
?>
</body>
</html>

The output of the program is shown below


4. Arrays in PHP:
An array is traditionally defined as a group of items that share certain characteristics. Each item
consists of two components; the key and a value. Key is the index of the item in the array and
value is the value of the item. PHP doesn’t require that you assign a size or type to an array at
creation time.
Declaring an array:PHP doesn’t even require that you declare the array before using it,
although you’re free to do so. We just add items to the array. We can add an item to a list as
$array-name[index of the element]= value;
For example we can start and add an item in an array as given below
$players[0] = ‘Muhammad Yousuf’;
We can add more items in the similar way but use a different index
$players[1]=”Ricky Ponting”;
Accessing an array: we can read an array item just by entering the array name and the index of
the item. For example if we want to read and display the value of second item in the $players
array we can do this as given below
echo $players[1];
Associative array: PHP allow us to create arrays where items are declared by name instead of
index or key number. Such an array is called an associative array. An item in an associative array
can be added as
$array-name[item name] = value
For example
$players[‘yousuf’]=”Muhammad Yousuf”;
Items in associate array are accessed by name. For example, we can read the value of the above
array as
echo $players[‘yousuf’];
array() function: we can also use array function to create an array. By using this function we
can add multiple items in one line. The syntax of the array function is
$array_name=array(item_1,item_2,…item_n);
Example is $players=array(“M.Yoursuf”,”Imran Khan”);
We can also use array function to create associative arrays such as
$players=array(“Yousuf”=>“M.Yoursuf”,”imran”=>”Imran Khan”);
Sorting an array: PHP provides us sort() to sort an array in ascending order while rsort()
function to sort an array in descending order.

Passing variables between pages

In a web page we can have variables. These variables are available as long as we remain on that
page. When we move to some other page, we cannot find those variables. However, PHP
provides us some super global variables that can keep variables and we can retrieve these
variables on other pages. In this lecture we will learn how to pass variables between pages.
1. Passing form’s data:
Forms provide a mean of submitting information from the client machine to the server. We can
create HTML forms using <form> tag. Method and action are the most common attributes of
the <form>. Action is used to give the URL of the application that is to receive and process the
forms data. Method sets the HTTP method that the browser uses to send the form's data to the
server for processing. Get and post are the common methods. In get method all form data is
encoded into the URL, appended the action URL as query string parameters while in post
method form’s data appears within the message body of the HTTP request.

1.1 Super global variables:


PHP automatically makes few variables available in your program. These are array variables and
can be accessed by name. These variables are called super-global variables because they can be
accessed without regard to scope. The most commonly used super global variables are $_GET
and $_POST. Below we discuss these super global variables in detail.
$_GET super global variable: it contains all the query string variables that were attached to the
URL. As we discussed earlier, that when we use get method in a form, its input is transferred
along with the URL as query string parameters therefore, $_GET variable also keeps the input of
the from when it is sent by get method. On the action page we can retrieve user’s input from
$_GET variable.
We show this mechanism by the following example. Consider the following code for a form
<body>
<form method=“get” action=“action.php”>
<input type=“text” name=“name”>
<input type=“text” name=“email”>
<input type=“submit”>
</form>
</body>

This code creates a form with two input elements named ‘name’ and ‘email’. When a user
submits this form after providing its input the user’s input is saved in the $_GET super global
variable. These values are stored in the $_GET super global array by name. The names of the
cells are the same as of the input fields in the form.

name email
$_GET
User’s name User’s email address

We can retrieve these values on the action page from the $_GET array. For example, if we want
to retrieve the user’s name we can do this by $_GET[‘name’].
$_POST super global variable: $_POST is also an array type variable which is created
automatically by PHP. It contains all the submitted form variables and their data. When we use
post method in the form, form’s input data is stored in the $_POST super global array which can
be retrieved on the action page. If we consider the form code of the previous example and set
the value of the method to post in the form tag, the user’s input is stored in the $_POST array
on the submission of the form. It is shown in the following diagram.

name email
$_POST
User’s name User’s email address

On the action page we can retrieve user’s input from $_POST variable. For example, if we want
to retrieve the user’s name we can do this by $_POST[‘name’].
1.2 Processing form’s elements:
In the section we will discuss how we can retrieve the value of different form elements on the
action page.
Textbox: when the user submits a form, values of all text boxes is stored in $_GET or $_POST
super global arrays depending upon the method we used in the form. These values can be
retrieved by the name of the input field in the form. In the following example we creates a form
which asks the user to enter its name and a submit button. The action page gets the user’s
input and displays a welcome message.
form.php action.php
<html> <?php
<head> $name = $_POST['name'];
<title>Passing Form Data</title> echo "Welcome Mr. $name";
</head> ?>
<body>
<form id="form1" name="form1" method="post"
action="action.php">
Enter Your Name:
<input type="text" name="name" value="Your
Name" /><br>
<input type="submit" />
</form>
</body>
</html>

The output of the above program is show in following figures. In the first figure user enter its
name and submits the form while the second diagram shows the action page with a welcome
message.
Hidden field: hidden fields are not visible to the user but their value can be retrieved on the
action page. We retrieve the value of a hidden field from $_GET or $_POST. Suppose a form
sends its input data to the server using get method and this form has a hidden input field with
name “hvalue”. We can retrieve the value of this hidden field on the action page by
$_GET[‘hvalue’].

Checkbox: we can retrieve the value of a checkbox on the action page by its name. If a user
checks a checkbox and submits the form the value of the checkbox is sent to the server. If the
value of the checkbox is not set in the input tag then ‘on’ is sent to the server

Radio button: Radio buttons shows some options to the user and the user can select only one
of them. We can retrieve the value of the selected radio button on the action page by its name.

In the following example we example we have used the form of the previous example and
added the following fields in it

 A hidden field named ‘hname’ and its value is set to Ali on the action page we retrieved
this value and displayed on the screen
 Two check boxes with name ‘C’ and ‘VB’. The value of checkbox C is not set while the
value of the checkbox VB is set to VB. On the action page the value of both check boxes
is displayed (the value will be displayed if the user checks the checkbox before
submitting the form). We have displayed a message if the user checks the C checkbox.
 A group of radio button asking about the nationality of the user. The value of the
selected radio button is also displayed on the browser

<html> <?php
<head> $name = $_POST['name'];
<title>Passing Form Data</title> echo "Welcome Mr. $name";
</head> echo "<br>";
<body> echo "Hidden name is ". $_POST['hname'];
<form id="form1" name="form1" method="post" echo "<br>";
action="action.php"> echo $_POST['C'];
Enter Your Name: <input type="text" echo "<br>";
name="name" echo $_POST['VB'];
value="Your Name" /><br> echo "<br>";
<input type="hidden" name="hname" if($_POST['C']=='C')
value="Ali" /><br /> echo "You Know C++";
Which of the following language do you know? else
<br /> echo "You do not know C++";
<input type="checkbox" name="C" value="C" />C+ echo "<br>";
+ echo $_POST['nat'];
<input type="checkbox" name="VB" />VB echo "<br>";
<br /> ?>
Your Nationality: <br />
<input type="radio" name="nat" value="single"
/>Single
<input type="radio" name="nat" />Dual
<br />
<input type="submit" />
</form>
</body>
</html>

The output of the above program is show in the following figures

Select list: select list provided multiple options to a user. The value of the selected list item is
passed to the server when the user submits the form and on the action page we can retrieve
this value by name of the select list.

2. Passing data using sessions


A session is basically a temporary set of variables that exists only until the browser has shut
down. These variables are accessible on other pages. While sending data on other pages using
sessions, we store data in the $_SESSION super global array and can retrieve the stored data on
any other page. $_SESSION super global array works as a common memory. We store data from
different pages in this array. The stored data can be accessed on any other page.
Following are some basics functions used while sending data using sessions
• session_start()- is used to start a session. This function is used on every page where we
use sessions. This function is called at the top of the page even before the <HTML> tag.
• $_SESSION[‘variable_name’]- is used to store data in session variable
• session_destroy()- is used to destroy a session
• unset($_SESSION[‘variable_name’])- is used to unset a specific variable
In the following example we have created the following pages
 on first page we start a session. In the body section we create a link to another page and
a session variable $_SESSION[‘name’] is declared which can be accessed on other pages.
 on second page we again start the session. In the body section we display the value of
the session variable declared/stored in the previous page and a link to the third page
 On third page we start the session and destroy the session. It means the previously
stored values are removed from the session array. In body section we display the value
of the session variable (as values is removed from the array therefore we could not get
that value)
<?php <?php <?php
session_start(); session_start(); session_start();
?> ?> session_destroy();
<html> <html> ?>
<head> <head> <head>
<title>Using Sessions</title> <title>Getting Session</title> <title>Destroying Session</title>
</head> </head> </head>
<body> <body> <body>
<?php <h1> This is the second <?php
$_SESSION['name']='Ali'; page</h1> echo $_SESSION['name'];
?> <?php ?>
<h1>Welcome to the first page echo "The value received from </body>
</h1> sessoin variable is ". </html>
<a href="session2.php">Go to $_SESSION['name'];
the next page</a> ?><br>
</body> <a href="session3.php">Go to
</html> the third page </a>
</body>
</html>

You might also like