Module 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Variable is nothing it is just name of the memory location.

A Variable is simply a
container i.e used to store both numeric and non-numeric information.

Rules for Variable declaration


$x=3; int x =0;
$x="3";
$x=1.0;

• Variables in PHP starts with a dollar($) sign, followed by the name of the
variable.
• The variable name must begin with a letter or the underscore character.
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _) Standard Naming Convention

$firstNumber = 90;
• A variable name should not contain space $myFirstNumber = 90; $personalInfo

$first_number =

Assigning Values to Variables


Assigning a value to a variable in PHP is quite east: use the equality(=) symbol, which
also to the PHP's assignment operators.

This assign value on the right side of the equation to the variable on the left.

A variable is created the moment you assign a value to it:

Example 1

<?php

$myCar = "Honda";

echo $myCar;

?>

Output Honda
In the above example Create a variable ($mycar) containing a string with
value="Honda". To print the carname pass $mycar inside echo statement.
PHP Concatenation
Example 2 (concatenate variable with string)

<?php

$myCar = "Honda City";

echo $myCar." is riding";

?>

Output Honda City is riding


In the above example Variable($mycar) hold value="honda city". Now we wants to
concatenate variable with string. pass this variable($mycar) inside echo statement. To
concatenate this with a string("is riding") use dot(.) between variable name and string.
The output will be displayed : Honda City is riding

Example 3 (Sum of two numbers)

<?php

$first = 100;

$second = 200;

$third = $first + $second;

echo "Sum = ".$third;

?>

Output Sum = 300


In the above example Declare $first , $second variable with value=100, 200 respectively.
Now add these two numbers using arithmetic operator ("+"). sum of these two variable
results stored in a third variable($sum). Now print the sum passing ($third) with echo
statement with a string.

Example 4 (Subtraction of two numbers)

<?php

$first = 1000;

$second = 500;
$third = $first - $second;

echo "Subtraction = ".$third;

?>

Output Subtraction = 500


In the above example We perform subtraction using variables($first, $second) with
vale=1000,500. Subtract second variable from first, result is hold by third variable($third)
. Print this third variable passing with echo statement.

Destroying PHP Variables


To destroy a variable, pass the variable to PHP's unset( ) function. as in the following
example:

Example 5

<?php

$name="steve";

echo $name;

//unset( ) function destroy the variable reference.

unset($name);

?>

Output steve
In the above example declare variable $name hold value="steve". In this program we
used unset() function to delete a particular variable. first it shows the output: "steve",
because we pass unset function after echo statement. Now pass variable name inside
unset($name) function output will show an Notice error(Variable is undefined).

Example 6

<?php

$first = 100;

$second = 200;

$third = $first + $second;


echo "Sum = ".$third;

unset($third);

//after delete the variable call it again to test

echo "Sum = ".$third;

?>

Output Sum = 300


Sum = Notice error undefined third variable

Note: Trying to access or use a variable that's been unset( ), as in the preceding script,
will result in a PHP "undefined variable" error message. This message may or may not be
visible in the output page, depending on how your PHP error reporting level is
configured.

Variable names in PHP are case-sensitive


<?php

$name="Rish";

$NAME="rahul";

echo $name."<br/>";

echo $NAME;

?>

Output Rish rahul


Variable names in PHP are case-sensitive. As a result, $name refers to a different variable
than does $NAME.

Inspecting Variable Contents (Variable Property)


PHP offers the var_dump( ) function, which accepts a variable and X-rays it for you.
Here's an example
Example 7 (For String value )

<?php

//define variables

$name = "Avah";

$age=25;

//display variable contents

var_dump ($name);

var_dump($age);

?>

Output string 'Avah' (length=5) int 25


In the above example We use var_dump( ) function to check the Contents(property) of
variable, $name hold a string value ="Avah" while $age hold an integer value = 25. Now
pass this variable inside var_dump($name,$age) function . It show all information related
this(data type of variable, length(only string), value)

Example 8 ( For Integer values )

<?php

$first = 100;

$second = 200;

$third = $first + $second;

var_dump ($third);

?>

Output int 300

Example 9 ( For Floating value )

<?php

$first = 100.5;
$second = 200.2;

$third = $first + $second;

var_dump ($third);

?>

Output float 300.7


In the above example variables first hold $first=100.5, second hold $second=200.2. Now
add these two values, result is stored in third variable($third). Pass this variable inside
var_dump($third) to check the content. output will float 300.7

Example 10 (For Boolean value )

<?php

$bool = true;

var_dump ($bool);

?>

Output Boolean true


In the above variable $bool with value="true". var_dump($bool) function is used to
display the result so output will display Boolean true, because variable holds a Boolean
value
PHP $ and $$ Variables
Difference Between $var and $$var in PHP
PHP $$var uses the value of the variable whose name is the value of $var. It means
$$var is known as reference variable whereas $var is normal variable. It allows you to
have a "variable's variable" - the program can create the variable name the same way it
can create any other string.

1. For Example - PHP $ and PHP $$


<?php

$name="Aron";

$name="Ainah";

echo $name."<br/>";

echo $name."<br/>";

echo $Aron;

?>

Output

Aron

Ainah

Ainah

In the above example $name is just a variable with string value="Aron". $$name is
reference variable.

$$name uses the value of the variable whose name is the value of $name.

echo $name print the value: Aron echo $$name print the value:Ainah \ value of
this($name) variable is act as reference of second variable($$name) .

echo $Aron print the value :Ainah \ Here $Aron is also act as reference variable.
Example - 2

<?php

$x = "100";

$x = 200;

echo $x."<br/>";

echo $x."<br/>";

echo "$100";

?>

Output

100

200

200

In the Above Example


You first assign the value of a variable, ($x) as the name of another variable.

When you set $x to a value, it will replace that variable name with the value of the
variable you provide.

variable $x hold value = 100.

$$x(reference variable) hold value = 200. now we want to print the value.

echo $x gives output:100

echo $$x gives output:200.

echo $100 gives value.200. because it also act as a reference variable for value = 200.
Example 3.

<?php

$name="Aron";

${$name}="Ainah";

echo $name."<br/>";

echo ${$name}."<br/>";

echo "$Aron"."<br/>";

?>

Output Aron Ainah Ainah

Example 4.

<?php

$name="Randy";

${$name}="Ricky";

${${$name}}="Rish";

echo $name;

echo ${$name};

echo ${${$name}};

?>

Output

Randy

Ricky

Rish

In the Above Example


variable $name hold value ="Randy"
variable ${ $name } hold value ="Ricky" // it also declare like ${Randy}.

variable ${$ {$name} } hold value ="Rish" // it act as "variable's of variable of variable"
reference.

echo $name show output:Randy

echo ${ $name } show output:Ricky.

echo ${ $ {$name} } show output :Rish

PHP Super global variables


Super Global Variables in PHP
PHP super global variable is used to access global variables from anywhere in the PHP
script. PHP Super global variables is accessible inside the same page that defines it, as
well as outside the page. while local variable's scope is within the page that defines it.

The PHP super global variables are:


1) $_GET["FormElementName"]

It is used to collect value from a form(HTML script) sent with method='get'. information
sent from a form with the method='get' is visible to everyone(it display on the browser
URL bar).

2) $_POST["FormElementName"]

It is used to collect value in a form with method="post". Information sent from a form is
invisible to others.(can check on address bar)

3) $_REQUEST["FormElementName"]

This can be used to collect data with both post and get method.

4) $_FILES["FormElementName"]

: It can be used to upload files from a client computer/system to a server. OR

$_FILES["FormElementName"]["ArrayIndex"]

: Such as File Name, File Type, File Size, File temporary name.
5) $_SESSION["VariableName"]

A session variable is used to store information about a single user, and are available to
all pages within one application.

6) $_COOKIE["VariableName"]

A cookie is used to identify a user. cookie is a small file that the server embedded on
user computer.

7) $_SERVER["ConstantName"]

$_SERVER holds information about headers, paths, and script locations.

Example

$_SERVER["SERVER_PORT"]

$_SERVER["SERVER_NAME"]

$_SERVER["REQUEST_URI"]

How to swap two numbers in PHP


<?php
extract($_POST);
if(isset($swap))
{
//first number
$x=$fn;
//second number
$y=$sn;

//third is blank
$z=0;

//now put x's values in $z


$z=$x;

//and Y's values into $x


$x=$y;

//again store $z in $y
$y=$z;
//Print the reversed Values
echo "<p align='center'>Now Fi rst numebr is : ". $x ."<br/>";
echo "and Second number is : ". $y."</p>";
}
?>

<form method="post">
<table align="center">
<tr>
<td>Enter First number</td>
<td><input type="text" name="fn"/></td>
</tr>
<tr>
<td>Enter Second number</td>
<td><input type="text" name="sn"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Swap Numbers" name="swap"/></td>
</tr>
</table>
</form>

Swap two variables value without using third variable in php


<?php
//swap two numbers without using third variable
$x=20;
$y=10;

//add x and y, store in x i.e : 30


$x=$x+$y;

//subtract 10 from 30 i.e : 20 and store in y


$y=$x-$y;

//subtract 20 from 30 i.e : 10 and store in x


$x=$x-$y;

//now print the reversed value s


echo "Now x contains : ". $x ."<br/>";
echo "and y contains : ". $y;

?>
Without Using Third Variable but using Some Predefined
Functions
<?php

$a = 10;

$b = 20;

list($a, $b) = array($b, $a);

echo $a . " " . $b;

?>

Constant in PHP
1. Constants are PHP container that remain constant and never change
2. Constants are used for data that is unchanged at multiple place within our program.
3. Variables are temporary storage while Constants are permanent.
4. Use Constants for values that remain fixed and referenced multiple times.

Rules for defining constant


1. Constants are defined using PHP's define( ) function, which accepts two arguments: The
name of the constant, and its value.
2. Constant name must follow the same rules as variable names, with one exception the "$"
prefix is not required for constant names.

Syntax:

<?php

define('ConstName', 'value');

?>
Valid and Invalid Constant declaration:

<?php

//valid constant names


define('ONE', "first value");

define('TWO', "second value");

define('SUM 2',ONE+TWO);

//invalid constant names


define('1ONE', "first value");

define(' TWO', "second value");

define('@SUM',ONE+TWO);

?>

Create a constant and assign your name


<?php

define('NAME', "Rish");

echo "Hello ".NAME;

?>

Output Hello Rish

In the above example We define a constant using define( ) function. first argument for
name of constant and second for its value="PhilSCA". Now we print the value. Pass
name of constant inside print statement Output will become

Sum of two numbers using constant


<?php

define('ONE', 100);
define('TWO', 100);

define('SUM',ONE+TWO);

print "Sum of two constant=".SUM;

?>

Output Sum of two constant = 200

In the above example We declare three constant of name=(ONE,TWO,SUM). First Add


the value of two constant. Now sum of these two value work as a value for third define
constant(SUM). Now pass $sum inside print it will show the sum of two number.

Subtraction of two numbers using constant


Ex.iii

<?php

define('X', 1000);

define('Y', 500);

define('Z',X - Y);

print "Subtraction of given number =".Z;

?>

Output Subtraction of given number = 500

In the above example We define three constant with name(X,Y,Z). First subtract the value
of two defined constant . Now result of these two value work as a value for third define
constant(Z). Pass Z inside print so it will show the subtraction of two value.

Sum of two numbers and assign the result in a variable


<?php

define('ONE', 100);
define('TWO', 100);

$res= ONE+TWO;

print "Sum of two constant=".$res;

?>

Output Sum of two constant = 200

In the above example We define two constant with name(one,two) and value(100,100)
respectively. $res variable is also define. Now we perform addition of two defined
constant value and result store in a variable($res = one+two;). To print the result pass
$res inside print statement.

Building a Dollars-to-Euros Converter


<h2>USD/EUR Currency Conversion</h2>

<?php

//define exchange rate


//1.00 USD= 0.80 EUR
define('EXCHANGE_RATE',0.80);

//define number of dollars


$dollars=150;

//perform conversion and print result


$euros=$dollars*EXCHANGE_RATE;

echo "$dollars USD is equivalent to :$euros EUR";

?>

Output

USD/EUR Currency Conversion


150 USD is equivalent to :120 EUR

if you have been following along, the script should be fairly easy to understand. It
begins by defining a constant named "EXCHANGE_RATE" which surprise, surprise stores
the dollar-to-euro exchange rate(assumed here at 1.00 USD to 0.80 EUR). Next, it
defines a variable named "$dollars" to hold the number of dollars to be converted, and
then it performs an arithmetic operation using the * operator, the "$dollars" variable,
and the "EXCHANGE_RATE" constant to return the equivalent number of euros. This
result is then stored in a new variable named "$euros" and printed to the Web page.

PHP Magic Constant


There are several predefined constants available to your scripts. We will use these
constants as we need them; there's a sample:

PHP: Magic Constant


PHP Magic Constant

__LINE__ The current line number of the file.

__FILE__ The full path and filename of the file.

__FUNCTION__ The function name

__CLASS__ The class name

__METHOD__ The class method name

PHP_VERSION The PHP version

PHP_INT_MAX The PHP integer value limit

__LINE__
The current line number of the file.

<?php

echo "The Line number : ". __LINE__;

?>

Output The Line number : 2

__FILE__
The full path and filename of the file.
<?php

echo "Your file name :". __FILE__;

?>

Output Your file name : C:xampplitehtdocsmagic_constantfile.php

__FUNCTION__, __CLASS__, __METHOD__


The function name The class name The class method name

<?php

class demo

function test()

echo "Function of demo class : ". __FUNCTION__ ."<br/>";

function testme()

echo "Method of demo class : ". __METHOD__ ."<br />";

echo "Class : ". __CLASS__;

$object=new demo();

$object->test();

$object->testme();

?>

Output Function of demo class : test Method of demo class : demo::testme Class :
demo
PHP_VERSION
The PHP version

<?php

echo "Current PHP Version you are using : ".PHP_VERSION;

?>

Output Current PHP Version you are using : 5.3.1

PHP_INT_MAX
The PHP integer value limit

<?php

echo "Integer Maximum Value : ".PHP_INT_MAX;

?>

Output Integer Maximum Value : 2147483647

Difference between echo and print in PHP


PHP echo and print both are PHP Statement. Both are used to display the output in PHP.

echo
1. echo is a statement i.e used to display the output. it can be used with parentheses echo
or without parentheses echo.
2. echo can pass multiple string separated as ( , )
3. echo doesn't return any value
4. echo is faster then print

For Example
<?php
$name="John";
echo $name;
//or
echo ($name);
?>

Output John

In the above example Create and initialize variable($name) hold a string value="John".
We want to print the name for this ($name) variable declare inside the echo with or
without parentheses . It will display the same output.

For Example (pass multiple argument)

<?php
$name = "John";
$profile = "PHP Developer";
$age = 25;
echo $name , $profile , $age, " years old";
?>

Output John PHP Developer 25 years old

In the above example $name , $profile and $age are three variable with value=("John" ,
"php developer" and 25) respectively. now we want to print all three variable values
together. all variables names are define inside the echo statement separated by comm
or dot(, or .) it will show the output

For Example (check return type)

<?php
$name = "John";
$ret = echo $name;
?>

Output Parse error: syntax error, unexpected T_ECHO

In the above example In this program we check the return type of "echo". declare a
variable $name with value="John". now we check the return type. when we run the
program it show error, because echo has no return type.

Print
1. Print is also a statement i.e used to display the output. it can be used with parentheses
print( ) or without parentheses print.
2. using print can doesn't pass multiple argument
3. print always return 1
4. it is slower than echo

For Example
<?php
$name="John";
print $name;
//or
print ($name);
?>

Output John

In the above example Declare a variable ($name) value="John". now we want to print
the name. we simply define $name inside print statement with or without parentheses. it
will show the output: "John" .

For Example (pass multiple argument)

<?php
$name = "John";
$profile = "PHP Developer";
$age = 25;
print $name , $profile , $age, " years old";
?>

Output Parse error: syntax error

In the above example Declare three variable $name, $profile, $age and hold the
value("John","php developer",25). Now check whether it will allow execute multiple
argument. Pass three variable inside the print statement separated by comma. As we run
this program it show some error. It means multiple argument are not allow in print .

For Example (check return type)

<?php
$name = "John";
$ret = print $name;
//To test it returns or not
echo $ret;
?>

Output John
In the above example declare a variable $name hold value="John".now we check the
return type of print . So (print $name )is store in a variable($ret) . it will show $name
value with return type=1.

Form GET Method


GET method is unsecured method because it displays all information on address bar/
url. By default, method is get method. Using GET method limited data sends. GET
method is faster way to send data.

In the given example user has to enter his/her name in text box, after entering the input
he/she has to click on submit button to display the name entered by him/her. You can
see the inputted value in address bar(url) also.

Create HTML Form Where user enter their name


<html>

<head>

<?php

echo $_GET['n'];

?>

<title>get_browser</title></head>

<body bgcolor="sky color">

<form method="GET">

<table border="1" bgcolor="green">

<tr>

<td>Enter your name</td>

<td><input type="text" name="n"/></td>

</tr>

<tr>
<td colspan="2" align="center">

<input type="submit" value="show my name"/></td>

</tr>

</table>

</form>

</body>

</html>

In the given above example: user entered the name inside the text box , after en tering
the name he clicked on submit button and can see the output of the program means
their name. User can check the input given by the user shows inside the URL because of
get method.

Enter two number and print the sum of given numbers.


<html>

<head>

<title>get_browser</title>

<?php

error_reporting(1);

$x=$_GET['f'];

$y=$_GET['s'];

$z=$x+$y;

echo "Sum of two number = ".$z;

?>

</head>

<body bgcolor="sky color">


<form method="GET" >

<table border="1" bgcolor="green">

<tr>

<td>Enter your first number</td>

<td><input type="text" name="f"/></td>

</tr>

<tr>

<td>Enter your second number</td>

<td><input type="text" name="s"/></td>

</tr>

<tr align="center">

<td colspan="2" >

<input type="submit" value="+"/></td>

</tr>

</table>

</form>

</body>

</html>

In the given above example: user has to enter the first number, second number after
given the input click on "+" button, and check the output means the sum of two
numbers. can also see the input given by him/her displays on address-bar(URL).

Form POST Method


POST method is secured method because it hides all information. Using POST method
unlimited data sends. POST method is slower method comparatively GET method.
Submit Form using POST Method.
<html>

<head>

<?php

echo $_POST['n'];

?>

<title>get_browser</title>

</head>

<body bgcolor="sky color">

<form method="post">

<table border="1" bgcolor="green">

<tr>

<td>Enter your name</td>

<td><input type="text" name="n"/></td>

</tr>

<tr>

<td colspon="2" align="center">

<input type="submit" value="show my name"/></td>

</tr>

</table>

</form>

</body>

</html>

In the given above example: user enters the name inside text box, after en tered the
name inside text box click on submit button it will display the name entered by user like
user enters "PhilSCA" inside the text box the output displays "PhilSCA". In this example
we have used Form POST method. So the user's input doesn't display on address-bar.

Submit Form using POST method(Sum of Two number).


<html>

<head>

<title>get_browser</title>

<?php

error_reporting(1);

$x = $_POST['f'];

$y = $_POST['s'];

$z = $x + $y;

echo "Sum of two number = ".$z;

?>

</head>

<body bgcolor="sky color">

<form method="post" >

<table border="1" bgcolor="green">

<tr>

<td>Enter your first number</td>

<td><input type="text" name="f"/></td>

</tr>

<tr>

<td>Enter your second number</td>

<td><input type="text" name="s"/></td>

</tr>
<tr align="center">

<td colspon="2" >

<input type="submit" value="+"/></td>

</tr>

</table>

</form>

</body>

</html>

In the given above example: user enters the first number inside first text box and second
number inside second text box, after entered the value inside the text box, clicked on
"+" button. The program displays the output Sum = addition of two numbers.

Create a Login Form (using POST Method)


<?php

error_reporting(1);

$id = $_POST['id'];

$pass = $_POST['pass'];

if(isset($_POST['signin']))

if($id=="Deep" && $pass=="Deep123")

header('location:https://www.philsca.edu.ph');

else

{
echo "<font color='red'>Invalid id or password</font>";

?>

<body>

<form method="post">

<table border="1" align="center">

<tr>

<td>Enter Your Id</td>

<td><input type="text" name="id"/>

</td>

</tr>

<tr>

<td>Enter Your Password</td>

<td><input type="password" name="pass"/>

</td>

</tr>

<tr>

<td><input type="submit" name="signin" value="SignIn"/>

</td>

</tr>

</table">

</form>

</body>
In the given above example: there is a secure login page. in which user enters the valid
user_name and password, after entering the valid user_name and password he has to
clicked on Sign-In button. authorized user can visit next page and for unauthorized u ser
it shows an error message.

How to use HTML Form action


Action is used to give reference/link of another page. If we want to separate the
business logic (PHP script) from Presentation layer (HTML script) then use action
Property of Form . It reduce the complexity of bulk of codes. Because All scripts are
separately define on their own page. In the previous Form Post method PHP script and
HTML script were define on the same page ,so it show the design part with the output
of program. But using action property HTML script define on a separate page and
Business logic(PHP script) on another separate page.

Create HTML Form with action Property


Save it as DesingView.php

<body>

<form method="post" action="Logic.php">

<table border="1" align="center">

<tr>

<td>Enter your name</td>

<td><input type="text" name="n"/></td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" name="sub" value="SHOW MY NAME"/>

</td>

</tr>

</table>
</form>

</body>

PHP Script
Save it as Logic.php

<?php

$name=$_POST['n'];

echo "Welcome ".$name;

?>

First we make Form using HTML script. We design a textbox to take input through user
and a submit button with value("show my name") . When name is entered by user and
click on submit button the value of textbox redirect to php script page. Because Action
Attribute is used here for link . Information that is send by user is collect by using
$_POST[] and store in a local variable($name). Now a local variable is concatena te with
String(“welcome”) and print, output will become Welcome Ainah.

PHP Display result in Textbox


How to display Result in textbox in PHP
How to get input from HTML, do calculation and display output in text box.

Write a program to add two numbers and print the result in third text box.

To display the output in third text box there are many ways. First way : Take input from
HTML make calculation and display the output in text box, for this use <input
type="text" value="output"/> inside PHP script. like:

<?php
if(isset($_POST['add']))
{
$x=$_POST['fnum'];
$y=$_POST['snum'];
$sum=$x+$y;
echo "Result:<input type='text' value='$sum'/>";
}
?>

<body>
<form method="post">
Enter first number <input type="text" name="fnum"/><hr/>
Enter second number <input type="text" name="snum"/><hr/>
<input type="submit" name="add" value="ADD"/>
</form>
</body>

Output
2000
Result:
1000
Enter first number
1000
Enter second number
ADD

In the given example,

First we design two textbox using HTML script with attribute name with ( value="Fnum"
for first textbox) and (value= "Snum" for second textbox). A submit button with
(name=Add).

When we run the program the logic that is defined inside PHP script, $_POST[ ] is used
to collect the values from a form. it store the value in variables ($x,$y).

But we want to show the sum inside the textbox. for this we define textbox inside the
"echo" statement with (value="$sum").

SWAP Sum of two number and display the Result in third text
box
<?php
$x=$_POST['fnum'];
$y=$_POST['snum'];
$sum=$x+$y;
?>

<body>
<form method="post">
Result <input type="text" value="<?php echo @$sum;?>"/><hr/>
Enter first number <input type="text" name="fnum"/><hr/>
Enter second number <input type="text" name="snum"/><hr/>
<input type="submit" value="ADD"/>
</form>
</body>

Output
2000
Result:
1000
Enter first number
1000
Enter second number
ADD

In previous example,

the textbox is defined inside the PHP script. Instead this We define third textbox outside
the PHP script.

Value attribute of <Input> tag is used to show the output inside the textbox here we
define a PHP script inside the value Property of the textbox.

Fill Registration form, show Output in text box


Create a Registration form fill all the information and display the result in text box on
next page

Save the program as registration form.html

<html>
<body>
<form method="post" action="output.php">
<table bgcolor="#C4C4C4" align="center" width="380" border="0">
<tr>
<td align="center"colspan="2"><font color="#0000FF" size="5">Registration
Form</font></td>
</tr>
<tr>
<td width="312"></td>
<td width="172"> </td>
</tr>
<tr>
<td><Enter Your Name </td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="email" name="email" /></td>
</tr>
<tr>
<td>Enter Your Password </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Enter Your Mobile Number </td>
<td><input type="number" name="num" /></td>
</tr>
<tr>
<td>Enter Your Address </td>
<td><textarea name="address"></textarea></td>
</tr>
<td align="center" colspan="2"><input type="submit" value="save" name="submit"
/></td>
</table>
</form>
</body>
</html>

Output

Registration Form
Enter Your Name phptpoint

Enter Your Email

Enter Your Password ************

Enter Your Mobile Number

Enter Your Address

save

Output.php

Save the program as output.php

<table bgcolor="#C4C4C4" align="center" width="380" border="0">


<tr>
<td align="center"colspan="2"><font color="#0000FF">Your Output</font></td>
</tr>
<tr>
<td>Your Name is</td>
<td><input type="text" value="<?php echo $_POST['name']; ?>" readonly="" /></td>
</tr>
<tr>
<td>Your Email is</td>
<td><input type="email" value="<?php echo $_POST['email']; ?>" readonly=""
/></td>
</tr>
<tr>
<td>Your Password is</td>
<td><input type="password" value="<?php echo $_POST['password']; ?>" readonly=""
/></td>
</tr>
<tr>
<td>Your Mobile Number is</td>
<td><input type="number" value="<?php echo $_POST['num']; ?>" readonly=""
/></td>
</tr>
<tr>
<td>Your Address is</td>
<td><textarea readonly="readonly"><?php echo
$_POST['address'];?></textarea></td>
</tr>
</table>

Output

Your Output will display like

Your Name is phptpoint

Your Email is

Your Password is ************

Your Mobile Number is

Your Address is

We create form using HTML script with (method="post") and action="output.php". We


define Five fields inside the HTML form.

First for name,Second for Email_id, Third for Password,Fourth for Mobile No,and Fifth for
address. A button is used to display data on next page after click on this button.
inside the (output.php) page we create same form format. But value attribute of every
<input> type tag is used to declare the PHP script inside the value with $_POST[ ] .

$_POST[ ] is define with name of a field like. $_POST['name'], $_POST['email']. As we run


this program the dada that is Entered in First page will dispaly as it is data on
Second(output.php) page.

Handle Multiple submit buttons PHP different


actions
<?php

extract($_POST);

//do addition and store the result in $res


if(isset($add))
{
$res=$fnum+$snum;
}

//do subtraction and store the result in $res


if(isset($sub))
{
$res=$fnum-$snum;
}

//do multiplication and store the result in $res


if(isset($mult))
{
$res=$fnum*$snum;
}

?>

<html>

<head>

<title>Display the result in 3rd text box</title


>

</head>

<body>
<form method="post">

<table align="center" border="1">

<Tr>

<th>Result</th>

<td><input type="text" value="<?php echo @$res;?>"/></td>

</tr>

<tr>

<th>Enter first number</th>

<td><input type="text" name="fnum"/></td>

</tr>

<tr>

<th>Enter second number</th>

<td><input type="text" name="snum"/></td>

</tr>

<tr>

<td align="center" colspan="2">


<input type="submit" value="+" name="add"/>
<input type="submit" value="-" name="sub"/>
<input type="submit" value="*" name="mult"/>

</tr>

</table>

</form>

</body>

</html>
Add two textbox values and display the sum in third
textbox using extract method
Enter two numbers and display the output in third text box when u click on submit button. Keep
in mind one thing First and second text values doesn't reset. Result text box should not writable .

PHP Script
<?php
extract($_POST);
//do addition and store the result in $res
if(isset($add))
{
$res=$fnum+$snum;
}

?>

HTML Form
<html>
<head>
<title>Display the result in 3rd text box</title>
</head>
<body>
<form method="post">
<table align="center" border="1">
<Tr>
<th>Your Result</th>
<td><input type="text" readonly="readonly" value="<?php echo
@$res;?>"/></td>
</tr>
<tr>
<th>Enter first number</th>
<td><input type="text" name="fnum" value="<?php echo
@$fnum;?>"/></td>
</tr>
<tr>
<th>Enter second number</th>
<td><input type="text" name="snum" value="<?php echo
@$snum;?>"/></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="+" name="add"/>

</tr>
</table>
</form>
</body>
</html>

Arithmetic operators in PHP


PHP supports all standard arithmetic operations, as illustrated by the list of Operators .

Common Arithmetic Operators

Operatos Description

+ Add

- Subtract

* Multiply

/ Divide and return quotient

% Divide and return modulus

Here's example illustrating these operators in action


PHP Arithmetic operators are used to perform mathematical operation on more than
one operands.

Some of the standard arithmetic operators are +,-,*,/,%.

The use of some common arithmetic operators is here illustrated by an example as


follows:-

Arithmetic operators (+) for addition


<?php

$x=10;

$y=5;
//addition

$sum=$x+$y;

echo "sum=".$sum."<br/>";

?>

Output sum = 15

Arithmetic operators (-) for subtraction


<?php

$x=10;

$y=5;

//subtraction
$sub=$x-$y;

echo "sub=".$sub."<br/>";

?>

Output sub = 5

Arithmetic operators (*) for multiplication


<?php

$x=10;

$y=5;

//Multiply
$multiply=$x*$y;

echo "Multiplication = ".$multiply."<br/>";

?>

Output Multiplication = 50
Arithmetic operators (/) for quotient
<?php

$x=10;

$y=5;

//quotient
$div=$x/$y;

echo "Div = ".$div."<br/>";

?>

Output Div = 2

Arithmetic operators (%) for remainder


<?php

$x=10;

$y=3;

//remainder
$rem=$x%$y;

echo "remainder=".$rem."<br/>";

?>

Output sub = 0

$x and $y are two integer variables here there are five blocks/modules in this example
they are to preform addition, subtraction, multiplication, division and modulus
respectively.

$x store the value 10, $y store the value 5. The output of first module is addition of two
values 10 and 5 that is 15 ($x+$y=15).

The output of second module is subtraction of two values 10 and 5 that is 5 ($x-$y=5).
The output of third module is multiplication of two values 10 and 5 that is 50
($x*$y=50).

The output of fourth module is division of two values 10 and 5 that is 2 ($x/$y=2).

The output of last module is modulus of two values 10 and 3 that is 1 ($x%$y=1).

Assignment Operators in PHP


There are a few other Operators that tend to do some arithmetic operations
and store the result in same. for eg the addition-assignment operator, represented
by the symbol +=, lets you simultaneously add and assign a new value to a variable.

Common Assignment Operators

Operatos Description

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign quotient

%= Divide and assign modulus

.= Concatenate and assign(its used only for sting)

and here's example illustrating these operators in action.

Add and assign


<?php

$x = 500;

$x+= 500;

echo "sum=".$x."<br/>";

?>
Output sum=1000

In the above example


Initialize variable ($x) with value = 500. If we want to add 500 to this value . we don't need a
second and third variable to store the sum of value($x+=500) it means ($x=$x+500 ) .
add 500 and re-assign new value(1000) back to same variable ($x).

Subtract and assign


<?php

$x = 1000;

$x-= 500;

echo "subtraction = ".$x."<br/>";

?>

Output subtraction = 500

In the above example


Create and initialize variable($x) hold value = 1000. now perform subtraction. 500 is subtract
from 1000 using($x-=500) it means($x=$x - 500 ) .
Now assign new value back to the initialize variable($x). so the output will become:

Multiply and assign


<?php

$x = 100;

$x*= 10;

echo "Multiplication = ".$x."<br/>";

?>

Output Multiplication= 1000


In the above example
Variable( $x) with value=100. now perform multiplication. ($x*=10) now value 10 multiply with
previous value(100).
and the output will become:1000 and it re-assign back to the variable ($x)
so the output will become : 1000

Divide and assign quotient


<?php

$x = 1000;

$x/= 500;

echo "Quotient = ".$x."<br/>";


?>

Output Quotient = 2

In the above example.


Declare Variable( $x) with value=1000. now perform divide.($x/=500) now value 500 divide with
previous value(1000).
and the output will become:2 and it re-assign value=2, back to the variable ($x).

Divide and assign modulus


<?php

$x = 5;

$x%= 2;

echo "Remainder = ".$x."<br/>";

?>

Output Remainder= 1

In the above example. Variable($x) with value =5. Now calculate the modulus using ($x%=2) .
it gives remainder value="1" and this remainder assign again to variable($x).
and the output will become : 1
Concatenate and assign
<?php

$str = "Welcome ";

$str. = "to the world of PHP";

echo $str."<br/>";

?>

Output Welcome to the world of PHP.

In the above example.


Declare variable($str). With string value="Welcome" .
Now concatenate this string to another string using the same variable
by performing ($str.="to the world of php").
It concatenate "welcome" with "to the world of php" and
The output will become this: Welcome to the world of PHP.

PHP comparative operators


PHP lets you Compare one variable or value with another via its wide range
of comparison operators.

Common Comparison Operators

Operatos Description

== Equal to

=== Equal to and of the same type

!= Not equal to

!== Not equal to and of the same type

> Greater than

< Less than


>= Greater than or equal to

<= Less than or equal to

Here's example illustrating these operators in action


Eg ( == and === )

<?php

$x=10;

$y=10.0;

echo ($x==$y);
//it returns true because both the variable contains same value.

echo ($x===$y);
/*it returns false because === strongly compares.
here both variable contain same value i.e 10 but different datatype one is
integer and another is float.*/

?>

in the above example. Two variable $x , $y define $x hold the value 10 $y hold value 10.0 Now
perform several operation on this First check ($x==$y)=>it returns true because the value for
both is same Second Check($x===$y)=>it returns false because now it also compare data-type.
$y hold a float value.

Difference between ( == and === )


<?php

//another example
$bool=(boolean)1;

$int=(integer)1;

//return true because both have same value.


echo ($bool==$int);

//return false because both have same value but diff data type
echo ($bool===$int);

?>
$bool=(boolean)1 ($bool==$int) it returns true because both have same value $int= (integer)1
($bool===$int) its return false because both have different data type

Use of( >, <, >=, <= )


<?php

$a=10;

$b=11;

echo $a>$b;
//return false because $a is less than $b.

echo $a<$b;
//return true because $a is less than $b.

echo $a>=$b;
//return false because neighter $a is greater nor equal to $b

echo $a<=$b;
//return true because $a is than $b.

?>

$a hold the value 10 $b hold the value 11 check ($a>$b)=> returns false because $a less
than $b. check($a>=$b)=> returns true because $a neither grater nor equal to $b.

PHP logical operators


Logical operators really come into their own when combined with conditional tests.
following example illustrating these operators.

Logical Operators

Operatos Description

&& and
|| or

! not

AND(&&) Operator
Operator name and pass

Description If name and pass both are true then result true.

Explanation if name = = "alex" and pass = = "alex123" then it will redirect on PhilSCA page, and if any
one of these is not valid then it shows an error message(Invalid name or password).

Eg of and operator

<?php

$name="alex";

$pass="alex123";

if($name=="alex" && $pass=="alex123")

header('location:https://www.philsca.edu.ph');

else

echo "Invalid name or password";

?>

Output This program will redirect you on "https://www.philsca.edu.ph" page

In the above example Two variable $name and $pass with value("alex","alex123") If both
value are exist then it will redirect on PhilSCA.com because of header( ). Otherwise
invalid name or password. Here both the condition are true so as output you will be
redirected on "https://www.philsca.edu.ph" page.
OR(||) Operator
Operator name or pass

Description If name or pass are true then result true.

Explanation if name = = "alex" or pass = = "alex123" then it will redirect on PhilSCA page, and if both are
false then it shows an error message(Invalid name or password).

Eg

<?php

$name="alex";

$pass="alex123";

if($name=="alex" || $pass=="alex12345")

header('location:https://www.philsca.edu.ph');

else

echo "Invalid name or password";

?>

Output This program will redirect you on "https://www.philsca.edu.ph" page

in the above example Two variable $name or $pass $name hold the value="alex" $pa ss
hold the value="alex123" if any of one condition is true then redirect you on
"https://www.philsca.edu.ph" page otherwise so invalid name or password. Here one of
the both condition is true so as output you will be redirected on
"https://www.philsca.edu.ph" page.
Not(!) Operator
Operator not

Description reverse the logical test

Explanation check given number is odd or not. Here $num stores 11 and its modulus is 1 . By example
$num mudulus is not equal to 0 it is an odd number so 11 is an odd numder.

Eg

<?php

$num=11;

if($num%2!=0)

echo $num." is odd number";

else

echo $num." is even number";

?>

Output 11 is odd number

In the above example take a variable $num with value = 11 let we check number is odd
or even. we give a condition($num%2!=0) inside if it will not true then number is odd.
otherwise else statement is execute ( Number is even ). Here number is not divided by 2
so the output display : given number is odd number

Create a Login page using && and || operator


<?php
if(isset($_GET['login']))

$eid=$_GET['e'];

$pass=$_GET['p'];

if($eid=="" || $pass=="")

echo "<font color='red'>Please fill your email and pass</font>";

else

if($eid=="xyz" && $pass=="xyz123")

echo "<font color='blue'>welcome xyz</font>";

else

echo "<font color='red'>wrong email or pass</font>";

?>

<form>

Enter your email<input type="text" name="e"/><br/>

Enter your pass<input type="password" name="p"/>

<input type="submit" value="Signin" name="login"/>

</form>
Output
wrong email or pass
sanjeev
Enter your email
******
Enter your pass
Signin

In the above example Here, we create a form of two field. By default, the method of
form is 'GET' First filed is for Email Second filed is for password A logic is define in PHP
script. First it's check the isset( ) function for existence, Enter the name and password in
name and password field it store value in variables ($eid and $pass). if either $eid or
$pass value is null then a message is shown "fill your email or password". Otherwise it
checks the $eid and $Pass value with the given existing value. if match then message
show "welcome xyz" else message show "wrong email or password."

Operator Precedence in PHP


You would have probably learned about BOD-MAS, a mnemonic that specifies the
order in which a calculator or a computer performs
a sequence of mathematical operations.

Brackets, order , Division , Multiplication , Addition , and Subtraction.

PHP's precedence rules are tough to remember. Parentheses always have the highest
precedence, so wrapping an expression in these will force PHP to evaluate it first, when
using multiple sets of parentheses.

Here is an example, consider the expression

<?php

echo (((4*8)-2)/10);

echo (4*8-2/10);

?>

Output with parentheses :3


without parentheses :31.8
Explanation of output
With parentheses:-
First step: 4 multiplied by 8 is 32.
Second step: 2 subtracted from 32 is 30.
and final step: 30 divided by 10 is 3.
Without parentheses:-
First step: 2 divided by 10 is 0.2.
Second step: 4 multiplied by 8 is 32.
and final step: 0.2 subtracted from 32 is 31.8

You might also like