0% found this document useful (0 votes)
277 views

PHP Introduction

PHP is a widely used scripting language for web development. It stands for PHP Hypertext Preprocessor. Over 20 million websites use PHP, making it one of the most popular languages. PHP is free, open source, and runs on many platforms. It is easy to learn and has a large community for support. The document provides an introduction to PHP and discusses its history, advantages over other languages, how to install PHP servers like WAMP and XAMPP, and basics of PHP syntax and comments.

Uploaded by

ds0909@gmail
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views

PHP Introduction

PHP is a widely used scripting language for web development. It stands for PHP Hypertext Preprocessor. Over 20 million websites use PHP, making it one of the most popular languages. PHP is free, open source, and runs on many platforms. It is easy to learn and has a large community for support. The document provides an introduction to PHP and discusses its history, advantages over other languages, how to install PHP servers like WAMP and XAMPP, and basics of PHP syntax and comments.

Uploaded by

ds0909@gmail
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 113

PHP Introduction

Let's Start PHP Introduction PHP Three letters that together constitutes the name of one of
the world’s most popular programming languages for Web development, the PHP
Hypertext Preprocessor.

While you might chuckle at the greenness of the recursive acronym, statistics indicate that
PHP is not be taken lightly: the language is today in use on over twenty million Web sites and
more than a third of the world’s Web servers-no small feat, especially when you consider that
the language has been developed entirely by a worldwide community of volunteers and is
freely available on the Internet at no cost whatsoever!

Over the last few years, PHP has become the de facto choice for the development of data-
driven Web applications, notably on account of its scalability, ease of use, and widespread
support for different databases and data formats.

This first chapter will gently introduce you to the world of PHP, by taking you on a whirlwind
tour of PHP’s history and features, and then guiding you through writing and executing your
first PHP program So flip the page, and let’s get Started.

History of PHP
PHP was originally created by a developer named Rasmus Lerdorf.

Version Release Date


1.0 8 June 1995
2.0 1 November 1997
3.0 6 June 1998
4.0 22 May 2000
5.0 13 July 2004
6.x cancel
7 3 December 2015(stable)
7.3 6 December 2018(current version)

Advantage of PHP
If you are familiar with other server side language like ASP.NET or JSP you might be
wondering what makes PHP so special, or so different from these competing alternatives well,
here are some reasons:

1. Performance
2. Portability(Platform Independent)
3. Ease Of Use
4. Open Source
5. Third-Party Application Support
6. Community Support

Performance
Scripts written in PHP executives faster than those written in other scripting language, with
numerous independent benchmarks, putting the language ahead of competing alternatives
like JSP, ASP.NET and PERL.

The PHP 5.0 engine was completely redesigned with an optimized memory manager to
improve performance, and is noticeable faster than previous versions.

In addition, third party accelerators are available to further improve performance and
response time.

Portability
PHP is available for UNIX, MICROSOFT WINDOWS, MAC OS, and OS/2. PHP Programs are
portable between platforms.

As a result, a PHP application developed on, say, Windows will typically run on UNIX without
any significant issues.

This ability to easily undertake cross-platform development is a valuable one, especially when
operating in a multi platform corporate environment or when trying to address multiple
market segments.

Ease Of Use
“Simplicity is the ultimate sophistication”, Said Leonardo da Vinci, and by that measure, PHP
is an extremely sophisticated programming language.

Its syntax is clear and consistent, and it comes with exhaustive documentation for the 5000+
functions included with the core distributions.

This significantly reduces the learning curve for both novice and experienced programmers,
and it’s one of the reasons that PHP is favored as a rapid prototyping tool for Web-based
applications.

Open Source
PHP is an open source project – the language is developed by a worldwide team of
volunteers who make its source code freely available on the Web, and it may be used without
payment of licensing fees or investments in expensive hardware or software .

This reduces software development costs without affecting either flexibility or reliability. The
open-source nature of the code further means that any developer, anywhere , can inspect the
code tree, spit errors, and suggest possible fixes, this produces a stable, robust product
wherein bugs, once discovered, are rapidly resolved – sometimes within a few hours of
discovery !.

Third-Party Application Support


One of PHP’s Strengths has historically been its support for a wide range of different
databases, including MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.

PHP 5.3 Supports more than fifteen different database engines, and it includes a common API
for database access.

XML support makes it easy to read and write XML documents though they were native PHP
data structures, access XML node collections using Xpath, and transform XML into other
formats with XSLT style sheets.

Community Support
One of the nice things about a community-supported language like PHP is the access it offers
to the creativity and imagination of hundreds of developers across the world.

Within the PHP community, the fruits of this creativity may be found in PEAR, the PHP
Extension and Application Repository and PECL, the PHP Extension Community Library, which
contains hundreds of ready-, made widgets and extensions that developers can use to
painlessly and new functionality to PHP.

Using these widgets is often a more time-and cost-efficient alternative to rolling your own
code. So complete the 2nd Page of the PHP Tutorial and Click on Next

PHP Server
The PHP Community Provides Some types of Software Server solution under The GNU
(General Public License).

These are the following:

1. WAMP Server
2. LAMP Server
3. MAMP Server
4. XAMPP Server

All these types of software automatic configure inside operating system after installation it
having PHP, MySQL, Apache and operating system base configuration file, it doesn't need to
configure manually.

Server Stands for

WAMP Microsoft window o/s, Apache Mysql PHP

LAMP Linux Operating System Apache Mysql PHP

MAMP Mac os Apache Mysql PHP

XAMPP x-os(cross operating system) Apache Mysql PHP Perl

Download and Install WAMP Server


Click here to download WAMP Server

Download and Install LAMP Server


Click here to download LAMP Server

Download and Install MAMP Server


Click here to download MAMP Server

Download and Install XAMPP Server


Click here to download XAMPP Server

WAMP Server Installation Steps


Step:1 Download latest wamp software(64bit for 64bit os and 32bit for 32bit os)

Step:2 click on setup

Step:3 click on next


Step:4 I accept the agreement and click on next

Step:5 choose drive of your computer

Step:6 click on next


Step:7 click on install

Step:8 choose your browser asked if firefox found click on yes otherwise no
Step:9 Completing the setup wizard click on finish

How To Execute PHP Script On WAMP Server


Step 1 : First Create PHP script using any editor like notepad, notepadd++ :

<?php
echo "Welcome to the world of PHP";

?>

Step 2 : Save file as following... Create a directory inside www like(myproject) Save it
inside: C:wamp/www/myproject/firstProg.php Start WAMP server (first time only) Step
3 : Run the PHP script Open Your browser and write in url
: localhost/myproject/firstProg.php

Output Welcome to the world of PHP

XAMPP Server Installation Steps


Download the XAMPP Setup

Double click the .exe file

Choose a language from the menu,

click OK.

Click on Next button.

Click on Next button again.

Click on Install.

Finally, click the Finish button.

Click Yes, to open the XAMPP Control Panel (see screenshot below).
Check Apache module and click on start for apache, check mysql module and click on
start for mysql

To Launch open your browser and type http://localhost/. you will got the welcome page

How To Execute PHP Script On XAMPP Server


Step 1 : First Create PHP script using any editor like notepad, notepadd++

<?php

echo "Welcome to the world of PHP";

?>

Step 2 : Save file as following... Create a directory inside xampp/htdocs/myproject/

Save it inside: C:xampp/htdocs/myproject/firstProg.php

Start XAMPP server (first time only)


Step 3 : Run the PHP script

Open Your browser and write in url : localhost/myproject/firstProg.php

Output welcome to the world of php

PHP Environment Start - End


syntax is a way to representation of PHP script. Basically it gives the primary idea to specify
the code format. It also specify the area of a written code.

There are three ways to start PHP environment.

The most commonly and effective PHP syntax:

<?php

echo "Welcome to the world of php";

?>

In the given Example It begin with (< ?php) and End with(? >). echo statement is used to print
the given string. Mandatory closing in("ABCD")double quotes.

Terminate the script with semicolon because semicolon is known as terminator.

Short or short-open tags look like this:

<?

echo "welcome to the world of php";

?>

In the given above example..

We use Short tags. start and end with () respectively.

Declare the statement in between (), to display the output on browser short open tags
smoothly works on XAMPP server but Face problem on wamp server if you are
using WAMP Server First you have to Set the short_open_tag setting in your php.ini file to
on

HTML script tags:

<script language="PHP">

echo "welcome to the world of php";


</script>

PHP is the server side Scripting language. So HTML script is also used to start PHP
environment like other scripting language.

Comments in PHP
A comment is non-executable lines. comment is used to write description for your own
understanding.Browser doesn't read the comments.

There are two types of comments used in php

1. Single line comments :


Single line comment used for short explanations. Declaration of Single line comment are two
types

Either Begin with(#)

Or backslash(//)

<?php

# This is the single line comment

# This is the next line comment

// This is also a single line comment.

?>

In the above Example. *First and second line comments begin with hash(#). *The third one is
begin with(//).

If we check the output of the given example. Browser show blank page. Because comments
are always non-executable..

another Eg of Single line Comment

<?php

$str= "welcome ";

//$str. =" student";

echo $str;

?>
Output welcome
In the above Example. We declare a variable to store the String("welcome") In second line we
concatenate string("student") with the Previous string("welcome") In third line we check the
output.It shows Welcome Only. Because the second line statement has already specify a
comment statement. So it can't take the string("student") as a declaration.

2. Multi-lines comments :
Multi lines comments used to comment multiple lines. Here we can give comments in bulk
The bulk comments are enclose within (/*.....*/)

<?php

/*

This is a comment with multiline

Developer : sanjeev rai

view : Multiline Comments Demo

*/

?>

The all lines which is define in php evironment are Multiline comments. it is non-
executable.Because it enlose with Multiline comments statement.

another eg of Multi-line comments

<?php

/*

$str = "welcome ";

$str.= "users ";

*/

echo "Hello user how are you ? ";

?>

Output Hello user how are you ?

PHP Variables
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

 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 _ )

 A variable name should not contain space

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:

Eg i

<?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
Eg ii (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

Eg iii (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 result
stored in a third variable($sum). Now print the sum passing ($third) with echo statement with
a string.

Eg iv (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:

Eg v

<?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 show 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).

Eg vi

<?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="rexx";

$NAME="rahul";
echo $name."<br/>";

echo $NAME;

?>

Output rexx 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

Eg vii ( For String value )

<?php

//define variables

$name = "Fiona";

$age=25;

//display variable contents

var_dump ($name);

var_dump($age);

?>

Output string 'Fiona' (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 ="Fiona" 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)

Eg viii ( For Integer values )

<?php

$first = 100;

$second = 200;

$third = $first + $second;

var_dump ($third);
?>

Output int 300

Eg ix ( 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

Eg x ( 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

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 where as $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="Rajeev";

$name="Sanjeev";

echo $name."<br/>";

echo $name."<br/>";

echo $Rajeev;

?>

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

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

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

echo $rajeev print the value :Sanjeev \ Here $Rajeev 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="Rajeev";

${$name}="Sanjeev";

echo $name."<br/>";

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

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

?>

Output Rajeev Sanjeev Sanjeev


Example 4.

<?php

$name="Ravi";

${$name}="Ranjan";

${${$name}}="Rexx";

echo $name;

echo ${$name};

echo ${${$name}};

?>

Output
Ravi
Ranjan
Rexx

In the Above Example


variable $name hold value ="ravi"

variable ${ $name } hold value ="Ranjan" // it also declare like ${Ravi}.

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

echo $name show output:ravi

echo ${ $name } show output:Ranjan.

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

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.

Eg

$_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 First 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 values
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', "Rexx");

echo "Hello ".NAME;

?>

Output Hello Rexx

In the above example We define a constant using define( ) function. first argument for name of
constant and second for its value="phptpoint". 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 a number of 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.
PHP data types
Data types specify the size and type of values that can be stored.

Variable does not need to be declared ITS DATA TYPE adding a value to it.

PHP is a Loosely Typed Language so here no need to define data type.

To check only data type use gettype( ) function.

To check value, data type and size use var_dump( ) function.

for eg : variable contains integer, float, and string value

<?php

$num=100;

$fnum=100.0;

$str="Hello";

var_dump($num,$fnum,$str);

?>

Output int(100) float(100) string(5) "Hello"

In the above example declare three variable $num , $fnum , $str.

$num hold value="100". (contain integer value).

$fnum hold value=100.0 (contain float value).

$str hold value="Hello" (contain string value).

Data types in PHP


There are 3 types of DATA TYPE

1. Scalar(predefined)
2. Compound(user-defined)
3. Special type

Scalar(It holds only single value)

1. Integer
2. Float/double
3. String
4. Boolean

Integer Data type

Integer means numeric data types. A whole number with no fractional component.

Integer may be less than greater than or equal to zero.

The size of an integer is platform-dependent, although a maximum value of about two billion
is the usual value (that's 32 bits signed).

64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is
always 32 bit Integer value should be between -2,147,483,648 and 2,147,483,647

<?php

$num=100;

var_dump($num);

?>

Output int(100)

In the above example $num hold value=100. pass this variable with echo statement to print
the value:

Float/double Data type

It is also called numeric data types.A number with a fractional component.

<?php

$num=100.0;

var_dump($num);

?>

Output float(100)

$num hold value=100.0. pass $num inside echo statement to display the output.

String Data type

Non numeric data type String can hold letters,numbers and special characters.
String value must be enclosed eighter in single quotes or double quotes.

<?php

$str="Welcome user";

$str1='how r you?';

$str2="@";

var_dump($str);

var_dump($str1);

var_dump($str2);

?>

Output string(12) "Welcome user" string(10) "how r you?" string(1) "@"

In the above example We create three variable to hold three string values. To display the
output pass all three variables with echo output will display.

Boolean Data type

Boolean are the simplest data type.Like a switch that has only two states ON means true(1)
and OFF means false(0).

<?php

$true=true;

$false=false;

var_dump($true,$false);

?>

Output bool(true) bool(false)

In the above example declare variable $true hold value=true, variable($false) hold
value=false. Now check the datatype using var_dump( ) function. Output will in boolean form:
bool(true) bool(false)

Compound(Multiple values in single variable)

1. Array
2. Object
Array Data type

<?php

$arr=array(10,20,30,40,50);

var_dump($arr);

?>

Output array(5) { [0]=> int(10) [1]=> int(20) [2]=> int(30) [3]=> int(40) [4]=>
int(50) }

In the above example Variable( $arr) hold values an array . Now we want to print the first
element of an array. Then we pass variable($arr) name with index value[0], fetch the first
element corresponding to the index value. Output will 10

Object Data type

<?php

class Demo

public function show()

echo "This is show method<br/>";

$obj= new Demo();

//$obj->show();

//$obj->show();

var_dump($obj);

?>

Output object(Demo)#1 (0) { }

Special Data types

1. Null
2. Resource

Null Data type

The special Data type "NULL" represents a variable with no value.

<?php

$blank=null;

var_dump($blank);

?>

Output NULL

Resource Data Type

The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP. A common example of using the resource data type
is a database call. for eg:

<?php

$con = mysqli_connect("localhost","root","","users");

?>

The function will return a resource type data to be stored into $con variable.

Some Predefine functions to Check data type


=> is_int( ) : Check given value is integer or not

=> is_float( ) : Check given value is float or not

=> is_numeric( ) : Check given value is either integer or float

=> is_string( ) : Check given value is string or not

=> is_bool( ) : Check given value is Boolean or not

=> is_array( ) : Check given value is array or not

=> is_object( ) : Check given value is object or not

=> is_null( ) : Check given value is null or not


Check if given variable holds a integer type of value then print the sum otherwise show
error message

<?php

$x = 1000;

$y = 500;

if(is_int($x) && is_int($y))

$sum = $x + $y;

echo "sum = ".$sum;

else

echo "both number must be integer";

?>

Output sum = 1500

In the above example Create two variable $x hold value=100, $y hold value=500, now
execute if..else condition. We pass is_int( ) function inside if condition, to check the value is
integer or not , if yes statement is execute and print the sum of two values. if not else
statement is execute show an error message.

PHP Form Example


PHP form is used to take input from users. in PHP if you want to take input from keyboard
and display the output according to input, in that case you have to use html form. html
form's have a property : form method in which you have to set either get or post
method. To illustrate, consider the following Web form(choose.php) which asks you to
select a brand of automobile and enter your desired color.

HTML Form
Save it as Choose.php

<html>
<head>

<title>form method</title>

</head>

<body>

<form method="post">

<h2>Select Your car</h2>

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

<tr>

<td>Select Your car</td>

<td>

<Selct name="selType">

<option value="porsche 911">Porsche 911</option>

<option value="Volkswagen Beetle">Volkswagen Beetle</option>

<option value="Ford Taurus">Ford Taurus</option>

</select>

</td>

</tr>

<tr>

<td>Color:</td>

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

</td>

</tr>

<tr>

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

</td>

</tr>

</table">

</form>

</body>
</html>

PHP Script

<?php

error_reporting(1);

$type=$_POST['selType'];

$color=$_POST['txtColor'];

echo "<font color='blue'>Your $color $type is ready. safe driving! </font>";

?>

Output Your blue Porshe 911 is ready. safe driving! Select your

car Color
In the given above example: First create a static page using HTML . Form first part is a drop
down box from where user has to select the option, 2nd part is a text box in which user enter
the color , after entered the value user click on button to display the output. output displays
lik Your blue Porshe 911 is ready. safe driving!

Form GET Method


GET method is unsecured method because it display 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 entering 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 entered the name
inside text box click on submit button it will display the name entered by user like user enters
"Phptpoint" inside the text box the output displays "Phptpoint". 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.phptpoint.com');

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 user 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 concatenate with String(“welcome”) and print,
output will become Welcome Sanjeev.
Use of extract() function in PHP
<?php
extract($_POST);
if(isset($save))
{
echo "<center>";
echo "Your Name : ".$fn."<br>";
echo "Your Last Name : ".$ln."<br>";
echo "Your Email : ".$eid."<br>";
echo "Your Course : ".$course."<br>";
echo "</center>";
}
?>
<html>

<head>

<title>use of extract() in Php</title>

</head>

<body bgcolor="sky color">

<form method="post" >

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

<tr>

<td>Enter your first Name</td>

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

</tr>

<tr>

<td>Enter your Last name</td>

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

</tr>

<tr>

<td>Enter your Email</td>

<td><input type="email" name="eid"/></td>

</tr>

<tr>
<td>Select Your Course</td>

<td>
<select name="course">
<option>Php</option>
<option>java</option>
<option>Perl</option>
</select>
</td>

</tr>

<tr align="center">

<td colspan="2" >

<input type="submit" value="Display Output" name="save"/></td>

</tr>

</table>

</form>

</body>

</html>

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
Result:
Enter first number
Enter second number

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").

WAP 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
Result:
Enter first number
Enter second number

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

Enter Your Email

Enter Your Password

Enter Your Mobile Number

Enter Your Address

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

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 multiplicatio 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>

Operators in PHP With Example


Variables are simply containers for information. In order to do anything useful with them,
you need Operators .

Operators are symbols that tell the PHP processor to perform certain actions.

For example, the addition(+) symbol is an Operators that tells PHP to add two variables or
values, while the greater-than(>) symbol is an Operators that tells PHP to compare two
values.

PHP supports more than 50 such Operators , ranging from operators


for arithmetical operations to operators for logical comparison and bitwise calculations.

This section discusses the most commonly used Operators .

There are four type of operators generally used by us.

1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators

Arithmetic operators in PHP


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

Common Arithmetic Operators


Operatos Descr
+ Ad
- Sub
* Mul
/ Divide and re
% Divide and re
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 assig

*= Multiply and assig

/= Divide and assign qu

%= Divide and assign mo

.= Concatenate and assign(its use

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 phptpoint";

echo $str."<br/>";

?>

Output Welcome to the world of phptpoint


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 Phptpoint

PHP comparative operators


PHP lets you Compare one variable or value with another via its wide range
of comparison operators.
Common Comparison Operators
Operatos Descriptio

== Equal to

=== Equal to and of the

!= Not equal

!== Not equal to and of t

> Greater th

< Less than

>= Greater than or

<= Less than or eq

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 neighter 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

&&

||

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 phptpoint page, and if a
message(Invalid name or password).

Eg of and operator

<?php

$name="alex";

$pass="alex123";

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

header('location:https://www.phptpoint.com');

else

echo "Invalid name or password";

?>

Output This program will redirect you on "https://www.phptpoint.com" page


In the above example Two variable $name and $pass with value("alex","alex123") If both
value are exist then it will redirect on phptpoint.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.phptpoint.com" 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 phptpoint page, and if both
password).

Eg

<?php

$name="alex";

$pass="alex123";

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

header('location:https://www.phptpoint.com');

else

echo "Invalid name or password";

?>

Output This program will redirect you on "https://www.phptpoint.com" page


in the above example Two variable $name or $pass $name hold the value="alex" $pass hold
the value="alex123" if any of one condition is true then redirect you on
"https://www.phptpoint.com" 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.phptpoint.com"
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 $
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
Enter your email
Enter your pass

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 check 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

Conditional statement in PHP


PHP lets programmers evaluate different conditions during of a program and take decisions
based on whether these conditions evaluate to true of false.

These conditions, and the actions associated with them, are expressed by means of a
programming construct called a conditional statement.
PHP supports different types of conditional statements

1. The if Statement : In if Statements Output will appear when only Condition must be true.
2. The if-else Statement : if-else statements allows you to display output in both the condition(if
condition is true display some message otherwise display other message).

3. The if-elseif-else Statement : The if-else-if-else statement lets you chain together multiple if-
else statements, thus allowing the programmer to define actions for more than just two
possible outcomes.

4. The switch Statement :The switch statement is similar to a series of if statements on the same
expression.

if statement in PHP
The if Statement is the simplest conditional statements.

In if Statements Output will appear when only Condition must be true.

If Statement works much like the English language statement, "if X happens, then do Y."

Write a program to check even number.(Number entered by user)

<?php

if(isset($_GET['save']))

if($_GET['n']%2==0)

echo $_GET['n']." is even number";

?>

<body>
<form method="get">

Enter Your number<input type="text" name="n"/><hr/>

<input type="submit" value="check number" name="save"/>

</form>

</body>

Output
10 is even number
Enter Your number

in the above example


we check if statement program
First we create a textbox and a button in a form using HTML script.
in this program we check given number is even or not.
The isset( ) function is used to check existence. $_GET[ ] is used to collect value that is entered
by user.
after this if condition check the number is even. if the number enter by user is even.
statement is execute, print even number.

WAP to check given number is Positive


Illustrate example to check if given number is greater than 0 then show notification message
number is positive.

<?php

$num=$_POST['n'];

if($num>0)

echo $num." is positive number";

?>

<body>

<form method="post">

Enter Your number<input type="text" name="n"/><hr/>


<input type="submit" value="check number"/>

</form>

</body>

Output
10 is positive number
Enter Your number

in the above example First we create a textbox and a button in a form using HTML tags.

in this program we check if number is grater than zero .it show a message "no is positive".

The isset() function is used to check existence.$_GET() function is used collect value that is
entered by user.

if the value is grater than 0. then statement will execute and show Message

Find the sum of even number between 1 to 100

<?php

$sum=0;

for($i=1;$i<=100;$i++)

if($i%2==0)

$sum=$sum+$i;

echo $sum;

?>

Output 2550
in the above example
whole program are in PHP script. Here we want to sum of even no.
We declare a variable($sum) initialize its value = 0.
For loop is used to check value from 1 to 100. The condition that declare inside the if check
the number is even or not.
if the no is even, statement will execute and print sum of all even no those exist between 1 to
100.
Initially $sum value=0. after check the even number condition.it store the even no in variable
( $i) and it sum with ($sum).
again and again it check the even number condition and calculate the sum.

If else statement in PHP


The if statement is quite basic because in If statement output will display when condition
must be true, if condition is false it display nothing(blank).

But if-else statements allows you to display output in both the condition(if condition is true
display some message otherwise display other message).

In English, this statement would read, "if X happens, do Y; otherwise do Z".

WAP to check given inputted number is negative or positive.

<?php

$num=$_POST['n'];

if($num>0)

echo $num." is positive number";

else

echo $num." is negative number";

?>

<body>

<form method="post">

Enter Your number<input type="text" name="n"/><hr/>

<input type="submit" value="check number"/>

</form>
</body>

Output
-10 is negative number
Enter your number

in the above example


First we create a textbox and a button in a form using HTML tags.
in this program we check given number is greater than zero if greater than zero , statement is
execute show message "number is positive" . else number is negative.
Through super global variable ( $_POST[ ] ) collect value from HTML script and store in a local
variable($num) that is entered by user.
after this if else condition is execute. if the condition($num > 0) is true execute the if
statement body otherwise execute the else body .
Here user enters the value -10 so the output will display : -10 is negative number.

WAP to Check given inputted number is even or odd

<?php

$num=$_POST['n'];

if($num%2==0)

echo $num." is even number";

else

echo $num." is odd number";

?>

<body>

<form method="post">

Enter Your number<input type="text" name="n"/><hr/>

<input type="submit"/>

</form>
</body>

Output
1 is odd number
Enter your number

in the above example,


First we create a textbox and a button in a form using HTML script.
in this program we check given number is even or not.
Using $_POST[ ] collected value that is entered by user.
after this check if number is entered by user divided by 2 and its modulus is 0 ($num%2==0),
it means if statements body execute and output will display the given number is even
number else given number is odd number.

Nested if else in PHP


The if-else-if-else statement lets you chain together multiple if-else statements, thus
allowing the programmer to define actions for more than just two possible outcomes.

Check given character is vowel or consonant.

<?php
$char=$_POST['ch'];
if($char=="a")
{
echo $char." is vowel";
}
else if($char=="e")
{
echo $char." is vowel";
}
else if($char=="i")
{
echo $char." is vowel";
}
else if($char=="o")
{
echo $char." is vowel";
}
else if($char=="u")
{
echo $char." is vowel";
}
else
{
echo $char. "is consonent";
}
?>
<body>
<form method="post">
Enter Your number<input type="text" name="ch"/><hr/>
<input type="submit"/>
</form>
</body>

Output
d is consonant
Enter your number

First we create a textbox and a button using HTML script.


using $_POST[ ] collect value that is entered by user and store in a variable($char).
Now check the condition($char=="a"),($char=="e"),($char=="i"),($char=="0") and so on.
Here we use nested if else because we need to select one of several blocks to be executed.
if the character enter by user are (a,e,i,o,u) it print, character is vowel else character is
consonant.
Here user has entered "d" so the output will display like : d is consonant

Print related day name according to inputted number (1 - 7).

<?php

$day=$_POST['day'];

if($day==1)

echo "Monday";

else if($day==2)

echo "tuesday";

else if($day==3)

echo "wednesday";

else if($day==4)

{
echo "Thursday";

else if($day==5)

echo "friday";

else if($day==6)

echo "Saturday";

else if($day==7)

echo "Sunday";

else

echo "Wrong choice";

?>

<body>

<form method="post">

Enter Your number<input type="text" name="day"/><hr/>

<input type="submit"/>

</form>

</body>

Output
Friday
Enter your number
First we create a textbox and a submit button using HTML script.
using $_POST[ ] collect value that is entered by user and store in a variable($day).
Now check the condition($day==1),($day==2),($day==3) and so on.
Here we use nested if else because we need to select one of several blocks to be executed.
if the number entered by user are (1 - 7) it print related statement, else wrong choice.
Here user has entered the value "5" so the output will display like : Friday

Switch Statement in PHP


The switch statement is similar to a series of if statements on the same expression.

The following two examples are two different ways to write the same thing, one using a series
of if and else-if statements, and the other using the switch statement.

<?php

$i=2;

if ($i == 0)

echo "$i equals 0 ";

else if ($i == 1)

echo "$i equals 1 ";

else if ($i == 2)

echo "$i equals 2 ";

//using switch
switch ($i)

case 0:

echo "$i equals 0 ";


break;

case 1:

echo "$i equals 1 ";

break;

case 2:

echo "$i equals 2 ";

break;

?>

Output
2 equals 2
2 equals 2
In the given example,

$i is a variable hold the value = 2, switch statement worked same as nested if else work.

if condition check($i==2), matched so the output will : 2 equals 2.

same for switch($i) matched the case 2: so the output will : 2 equals 2.

switch statement without break

<?php

$i=0;

switch ($i)

case 0:

echo "$i equals 0"."<br/>";

case 1:

echo "$i equals 1"."<br/>";

case 2:

echo "$i equals 2"."<br/>";

}
?>

Output
0 equals 0
0 equals 1
0 equals 2
variable($i) hold the value=0. this value pass inside the switch. it start match the case. first
case is match with initially declare variable value(0).

All statement are execute from case:0 to case:2.

Switch case may contain empty statement, then it simply passes the control for
next case.

<?php

$i=1;

switch ($i)

case 0:

case 1:

case 2:

echo "$i is less than 3 but not negative";

break;

case 3:

echo "i is 3";

?>

Output
1 is less than 3 but not negative
Initialize a variable($i) with value=1.Now pass this value inside the switch statement.

Now case start to match the value of initialize variable($i). As case:1 is match.

but their is no statement for execution. so it will skip the case because of break is absent in
case:1.
Now case:2 statement is execute and break terminate the program.

Output will become case:2 (statement) : 1 is less than 3 but not negative.

Use of Default in Switch Statement


In case any switch case doesn't matches then executes default statement.

<?php

$i=5;

switch ($i)

case 0:

echo "i equals 0";

break;

case 1:

echo "i equals 1";

break;

case 2:

echo "i equals 2";

break;

default:

echo "i is not equal to 0, 1 or 2";

?>

Output 5 is not equal to 0, 1 or 2


In the given example $i is variable hold value = 5. now switch condition execute with variable
$i.

Here three case is define. it check the value for case0, case1 and case2.

But only default condition is execute because all three case do not match. and Output display
: 5 is not equal to 0, 1 or 2
Enter first number second number and choice, make calculation.

<?php

$f=$_POST['f'];

$s=$_POST['s'];

$choice=$_POST['ch'];

switch ($choice)

case "+":

$sum=$f+$s;

echo "Sum=".$sum;

break;

case "-":

$sub=$f-$s;

echo "Subtraction=".$sub;

break;

case "*":

$mult=$f*$s;

echo "Multiplication=".$mult;

break;

case "/":

$div=$f/$s;

echo "Division=".$div;

break;

default:

echo "Invalid choice";

?>

<form method="post">
Enter first number<input type="text" name="f"/><hr/>

Enter second number<input type="text" name="s"/><hr/>

Enter your choice<input type="text" name="ch"/><hr/>

<input type="submit" value="Show Result"/>

</form>

Output
Sum=1000
Enter first number
Enter second number
Enter Your choice

In the above example first we create the form using HTML script to take input from users.
Inside the form ,we create three textbox and a submit button. Program logic define inside the
PHP script. Variable($f, $s , $choice) are declare to hold the value that is collect by using
$_POST[ ] . $choice is used to perform(Add/Multiply/Divide/substract) operation. First
Number input is 500 Second Number input is 500 Choice input is "+" Inside the choice text
box inputted value is +, so it will match the first case and execute first case(+). Output display
: Sum=1000

Create PHP Calculator


<?php
extract($_POST);
if(isset($save))
{
switch($ch)
{
case '+':
$res=$fn+$sn;
break;

case '-':
$res=$fn-$sn;
break;

case '*':
$res=$fn*$sn;
break;

}
}

?>
<!DOCTYP html>
<html>
<head>
<title>Calculator- switch</title>

</head>
<body>
<form method="post">
<table border="1" align="center">
<tr>
<th>Your Result</th>
<th><input type="number" readonly="readonly"
disabled="disabled" value="<?php echo @$res;?>"/></th>
</tr>

<tr>
<th>Enter your First num</th>
<th><input type="number" name="fn" value="<?php echo
@$fn;?>"/></th>
</tr>
<tr>
<th>Enter your Second num</th>
<th><input type="number" name="sn" value="<?php echo
@$sn;?>"/></th>
</tr>
<tr>
<th>Select Your Choice</th>
<th>
<select name="ch">
<option>+</option>
<option>-</option>
<option>*</option>
</select>
</th>
</tr>
<tr>

<th colspan="2">
<input type="submit"
name="save" value="Show Result"/>
</th>
</tr>
</table>
</form>
</body>
</html>

Find profit and loss in PHP


Write a Simple PHP Program to calculate Profile and Loss. Once Calculate Profit and Loss
then also calculate Profile percentage and loss percentage.

Eg
<?php
extract($_POST);
if(isset($save))
{
if($sp>$cp)
{
$p=$sp-$cp;
$pp=($p*100)/$cp;
$res= "Profit=".$p;
$res.= ", Prpfit % =".$pp."";
}
else
{
$l=$cp-$sp;
$lp=($l*100)/$cp;
$res= "Loss=".$l;
$res.= ", Loss % =".$lp."";
}
}

?>
<!DOCTYP html>
<html>
<head>
<title>Profit and Loss</title>

</head>
<body>
<form method="post">
<table border="1" align="center">
<tr>
<th>Your Output</th>
<th><textarea readonly="readonly"
disabled="disabled"><?php echo @$res;?></textarea></th>
</tr>
<tr>
<th>Enter your Cost Price</th>
<th><input type="number" name="cp" value="<?php echo
@$cp;?>"/></th>
</tr>
<tr>
<th>Enter your Selling Price</th>
<th><input type="number" name="sp" value="<?php echo
@$sp;?>"/></th>
</tr>
<tr>

<th colspan="2">
<input type="submit"
name="save" value="Check"/>
</th>
</tr>
</table>
</form>
</body>
</html>

What is the use of loop


When you want the same block of code to run over and over again in a row. Instead of
adding several almost equal lines in a script we can use loops to perform a task.

OR

When you want to execute same statements more than one times then use loop.

Four types of Loop used in PHP :

1. for : In for loop specified condition is predefined.


2. while : while loop executes the statement while a specified condition is true.In while loop first
check the condition then execute the statement.
3. do-while : do - while loop executes the statement once and next statement depends upon a
specified condition is true.In do - while loop first execute the statement then check the
condition, it means if condition is false in that case one time statement execute.
4. foreach : Foreach loop executes the statement() of an associative array.

For loop in PHP


The for loop is used when you know in advance how many times the script should run.
Syntax
for (initialization; condition; increment)

code to be executed;

Parameters of for loop :


Initialization :is used to set a counter.
Condition : if condition is true loop will continue, if the condition is false loop ends.
Increment : used to increment the counter.
Eg i (print the statement 5 times)
<?php
for ($i=1; $i<=5; $i++)

{
echo "The Number is: ".$i."<br/>";

?>

Output The number is 1


The number is 2
The number is 3
The number is 4
The number is 5
In the above example
We want to print the statement 5 times. we initialize how many times loop should iterate.
loop starts from ($i=1)and ends($i<=5)
so output displays five times defined statement.

Write a program to print your name 10 times

<?php

$name="rexx";

for ($i=1; $i<=5; $i++)

echo "My Name is: ".$name."<br/>";

?>

Output
My Name is rexx
My Name is rexx
My Name is rexx
My Name is rexx
My Name is rexx
In the above example
here output displays five times defined statement(My Name is ) with a variable(rexx)

Find the sum of 1 to 100.

<?php

$sum=0;
for ($i=1; $i<=100; $i++)

$sum=$sum+$i;

echo $sum;

?>

Output
5050
In the above example,
Variable( $sum ) holds value(0). For( ) loop is used to print sum of numbers.
set loop iteration, loop will continue to run as long as ( $i<=100) .
So output display 5050

Find all even numbers between 1 to 100

<?php

for ($i=2; $i<=100; $i+=2)

echo $i." ";

?>

Output
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92
94 96 98 100
In the above example,
Here loop starts from ($i=2 ) after every count $i increment its value by 2 and Print all even
value from( 1 to 100)

Find all odd numbers between 1 to 100 using loop.

<?php

for ($i=1; $i<=99; $i+=2)

{
echo $i." ";

?>

Output
1 3 5 7 9 ... 99
In the above example
Loop start from($i=1) to ($i<=99) every time $i increment its value by 2. if the value of ($i=1)
then it will become 3. therefore all odd value are print.

Find the Sum of even and odd numbers between 1 to 100.

<?php

for ($i=1; $i<=100; $i++)

if($i%2==0)

@$even=$even+$i;

else

@$odd=$odd+$i;

echo "Sum of even numbers=".$even."<br/>";

echo "Sum of odd numbers=".$odd;

?>

Output
Sum of even numbers=2550
Sum of odd numbers=2500
In the above example
For loop is used because we know how many times loop iterate. inside the for loop we
declare if..else condition.
If( $%2==0) condition is true, then code will execute and calculate the sum of even number.
otherwise else statement execute and calculate the sum of odd number.
Print the sum of odd ans even number separately.

Add two numbers using loop(Not use + operator).

<?php

@$f=$_GET['f'];

@$s=$_GET['s'];

for ($i=1; $i<=$s; $i++)

$f++;

echo "Sum of given numbers=".$f;

?>

<body>

<form>

Enter first number <input type="text" name="f"><br/>

Enter Second number<input type="text" name="s"><br/>

<input type="submit" value="add">

</form>

</body>

Output
Sum of given numbers=1000
Enter first number
Enter Second number

In the above example


First we create a HTML script to take input from users.
when a value entered by user and click on button ,value redirected to PHP script page.$_GET[
] is used to collect the value that is entered by user.
Now we check the sum. but sum is generate using (+) operator.
iteration start from ($i=1 to $i<=$s) it means loop depend on value of second textbox.
Value entered by user in first textbox is 500
Value entered by user in second textbox is 500
output become: 1000. because value of first textbox is incremented.
for loop will continue to run as long as ( $i<=$s ) condition is true.

Subtract two numbers using loop(Not use - operator).

<?php

@$f=$_GET['f'];

@$s=$_GET['s'];

for ($i=1; $i<=$s; $i++)

$f--;

echo "Subtraction of given numbers=".$f;

?>

<html>

<body>

<form>

Enter first number<input type="text" name="f"><br/>

Enter Second number<input type="text" name="s"><br/>

<input type="submit" value="Subtract">

</form>

<body>

Output
Subtraction of given numbers=500
Enter first number
Enter Second number

Print Pattern in PHP


Pattern 1

<?php
for ($i=1; $i<=5; $i++)
{
for($j=1;$j<=$i;$j++)
{
echo $j." ";
}
echo "<br/>";
}
?>

Output
1
12
123
1234
12345

Pattern 2

<?php
for ($i=1; $i<=5; $i++)
{
for($j=1;$j<=$i;$j++)
{
echo $i." ";
}
echo "<br/>";
}
?>

Output
1
22
333
4444
55555

Pattern 3

<?php
for ($i=1; $i<=5; $i++)
{
for($j=1;$j<=$i;$j++)
{
echo " * ";
}
echo "<br/>";
}
?>

Output
*
* *
* **
* ***
* ****

Pattern 4

<?php
for ($i=1; $i<=5; $i++)
{
for ($k=5; $k>$i; $k--)
{
//print one space throgh html ;
echo " ";
}
for($j=1;$j<=$i;$j++)
{
echo "*";
}
echo "<br/>";
}
?>

Output
*
**
***
****
*****

Pattern 5

<?php
for($i=0;$i<=5;$i++)
{
for($j=5-$i;$j>=1;$j--)
{
echo "* ";
}
echo "<br>";
}
?>

Output
*****
****
***
**
*

Pattern 6

<?php
for($i=0;$i<=5;$i++)
{
for($k=5;$k>=$i;$k--)
{
echo " ";
}
for($j=1;$j<=$i;$j++)
{
echo "* ";
}
echo "<br>";
}
for($i=4;$i>=1;$i--)
{
for($k=5;$k>=$i;$k--)
{
echo " ";
}
for($j=1;$j<=$i;$j++)
{
echo "* ";
}
echo "<br>";
}
?>

Output

Pattern 7

<?php
for($i=1; $i<=5; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '<br>';
}
for($i=5; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '<br>';
}
?>

Output

Pattern 8

<?php
for($i=5; $i>=1; $i--)
{
if($i%2 != 0)
{
for($j=5; $j>=$i; $j--)
{
echo "* ";
}
echo "<br>";
}
}
for($i=2; $i<=5; $i++)
{
if($i%2 != 0)
{
for($j=5; $j>=$i; $j--)
{
echo "* ";
}
echo "<br>";
}
}
?>
Output

Create table using for loop in PHP


<?php

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

$rows=$_POST['r'];

$cols=$_POST['c'];

echo "<table border='1'>";

for($i=0;$i<$rows;$i++)

echo "<tr>";

for($j=0;$j<$cols;$j++)

echo "<th>"."r".$i."c".$j."</th>";

echo "</tr>";

echo "</table>";

?>

<html>

<body>
<form method="post">

<table width="400" border="1">

<tr>

<td width="177">Enter number of rows </td>

<td width="207"><input type="text" name="r"/></td>

</tr>

<tr>

<td>Enter number of column </td>

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

</tr>

<tr>

<td colspan="2">

<input type="submit" value="Create Table" name="create"/>

</td>

</tr>

</table>

</form>

</body>

</html>

Output
r0c0 r0c1 r0c2
r1c0 r1c1 r1c2
r2c0 r2c1 r2c2
Enter number of rows
Enter number of column

while loop in PHP


The while loop executes a block of code while a condition is true.
Syntax

while (condition)

code to be executed;

Eg

<?php

$i=1;

while($i<=5)

echo "The number is " . $i . "<br>";

$i++;

?>

Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
In the above example,
$i hold the value=1, now check the condition while value of ($i<=5).
it means it execute the code five times. it print the statement line by line.

Find the sum of 1 to 100 using While Loop

<?php

$i=1;

$sum=0;

while($i<=100)

{
$sum=$sum+$i;

$i++;

echo "Sum= " . $sum;

?>

Output
Sum= 5050
In the above example,
Variable $i hold value=1, initially $sum hold value=0. we want to sum of 1 to 100 number
using while loop.
it execute the statement($sum=$sum+$i;) till the condition is true and value is increment by
($i++).
so it will give the output is 5050

WAP to Count Length and Sum of inputed numbers.

<?php

@$num=$_GET['num'];

$sum=0;

$rem=0;

$len=0;

while((int)$num!=0)

$len++;

$rem=$num%10;

$sum=$sum+$rem;

$num=$num/10;

echo "Length of given digit= " . $len."<br/>";

echo "Sum of given digit= " . $sum;

?>

<body>
<form>

Enter Your digit <input type="text" name="num"><br/>

<input type="submit" value="find the sum">

</form>

</body>

Output
Length of given digit= 5
Sum of given digit= 15
Enter first number

In the above example,


first we make a form and a textbox using HTML script. It gives the length and sum of the
value which is entered by user.
As value entered by user $_GET[] collect the value from a form. inside the PHP script we
declare 3 variable $sum,$rem,$len its value(0,0,0) respectively

Do while loop in PHP


The do...while Loop executes the statement once and then check the condition.

Syntax

do
{
code to be executed;
}
while (condition);

Eg

<?php

$i=1;

do

echo "The number is " . $i . "<br>";

$i++;
}

while ($i<=5);

?>

Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
In the above example,
variable $i hold value="1". first execute the statement inside do.
after that it check while condition($i<=5).
So the given statements execute 5 times.

Write a program to display table of given number.

<?php

@$tab=$_GET['tab'];

$i=1;

do

$t=$tab*$i;

echo $t." ";

$i++;

while ($i<=10);

?>

<body>

<form>

Enter Your table<input type="text" name="tab"><br/>

<input type="submit" value="Table">

</form>

</body>
Output
10 20 30 40 50 60 70 80 90 100
Enter your table

In the above example,


Create text-box and a button using HTML script. Logic is performed inside PHP script.
First we collect the value entered by user using $_GET. $i hold value=1.
to print the table of 10. ($t=$tab*$i) this condition multiply the entered value with $x(initial
value) value is increment after every iteration.
While check ($i<=10). so the while( ) loop executes the statement 10 times.
Output will generate table of 10.

Nested do - while
Write a program to display more than one table at a time.

<?php

$n=1;

$i=0;

$t=0;

do

do

$i++;

$t=$i*$n;

echo $t;

while($i<=10)

$i=0;

$n++;
while ($n<=10);

?>

In the above example,


we display more than one table, nested do while loop is used.
Declare three variable $n hold vale="1"
$i hold value="0"
$t hold value="0"

Foreach Loop in PHP


The foreach Loop is used to display the value of array.

You can define two parameter inside foreach separated through "as" keyword. First
parameter must be existing array name which elements or key you want to display.

At the Position of 2nd parameter, could define two variable: One for key(index) and another
for value.

if you define only one variable at the position of 2nd parameter it contain arrays value (By
default display array value).

Syntax
foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value (and the
array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next
array value.

The following example demonstrates a loop that will print the values of the given
array.
<?php

$person=array("alex", "simon","ravi");

foreach ($person as $val)

{
echo $val."<br/>";

?>

Output
alex
simon
ravi
In the above example,
declare an array variable($person) hold the elements of array. Here we want to print all
element of an array without passing index value.
We used foreach( ) loop. Passing Variable name ($person as $val).
it means $val collect all elements of an array. Pass $val with echo statement it show all
element as output.

Define colors name and their index

<?php

$color=array("r"=>"red", "g"=>"green","b"=>"black","w"=>"white");

foreach ($color as $key=>$val)

echo $key."--".$val."<br/>";

?>

Output
r--red
g--green
b--black
w--white
In the above example,
$color variable hold the values ("red","green","black","white") on index("r", "g", "b", "w" ).
if we want do display all values with their index then used foreach( ) loop.
Inside foreach( ) we have passed three arguments array name, index($key) and value($val)
separated by "as".
Now call the variable $val to display array values and $key for index.

Find the Sum of given array

<?php
$array=array(10,11,12,13,14,15);

$sum=0;

foreach ($array as $x)

$sum=$sum+$x;

echo "Sum of given array = ".$sum;

?>

Output
Sum of given array = 75
In the above example,
Declare variable $array hold the elements of an array, variable $sum hold value=0,
pass( $array as $x) inside foreach( ) loop.
It call the values of array one by one and make sum ($sum=$sum+$x) till ends of array.
at last pass $sum with echo statement to display the sum of given array, output will become.

PHP string functions


PHP has over 75 built-in String manipulation functions, supporting operations ranging from
string repetition and reversal to comparison and search-and-replace. Some of these
important functions are

Sr Function Wha
1 empty() Tests if a string is empty

2 strlen() Calculates the number of characters in a string

3 strrev() Retrun reverse of a given string

4 str_repeat() Repeats a string no. of times you want

5 substr() Retrieves a section of a string

6 strcmp() Compares two strings

7 str_word_count() Calculates the number of words in a string

8 str_replace() Replaces parts of a string

9 trim() removes leading and trailing whitespaces from a string

10 strtolower() Converts in Lowercases a string


11 strtoupper() Converts in Uppercases a string
12 ucfirst() Converts in uppercase the first character of a string

13 ucwords() Converts in uppercases the first character of every word

14 addslashes() Escapes special characters in a string with backslashes

15 stripslashes() Removes backslashes from a string

16 htmlentities() Encodes HTML within a string

17 htmlspecialchars() Encodes special HTML characters within a sting

18 nl2br() Replaces line breaks in a string with elements

19 html_entity_decode() Decodes HTML entities within a string

20 htmlspecialchars_decode() Decodes special HTML characters withing a string

21 strip_tags() Removes PHP and HTML code from a string

22 md5() The MD5 message-digest algorithm is a widely used for

23 str_split() str_split() function splits(break) a string into an array.

Here's example illustrating these operators in action

Eg ii ( strrev( ) )

<?php

$val="nitin";

if(strrev($val)==$val)

echo "Your name is palindrome";

else

echo "Your name is not palindrome";

?>

Output
Your name is palindrome
In the above example,
Declare variable $val hold value="nitin". Here we use strrev() Function to give reverse of a
string.
We pass strrev() function inside If condition. if the reverse string is equal to declared string.
it will print "Your name is palindrome" otherwise "Your name is not palindrome"
Eg iii (str_repeat( ) )

<?php

$val="welcome ";

echo str_repeat($val,3);

?>

Output
welcome welcome welcome
In the above example,
Declare variable $val with value="welcome".
use str_repeat( ) function with two argument. first argument declare name of variable, second
argument we define number of times print the value.
The output is (welcome welcome welcome) because we pass 3 second argument.

Eg iv ( str_replace( ) )

<?php

$str="welcome";

echo str_replace("e","@",$str);

?>

Output
w@lcom@
In the above example,
Declare variable $str with value="welcome".
use str_replace( ) function. It accepts three argument: the search term, the replacement term,
and the string on which perform replacement.
we have Passed str_replace("e","@",$str) and the output is : W@lcom@ because "@" replaced
by "e".

Eg v ( str_word_count( ) )

<?php

$str="hello user how r you";

echo str_word_count($str);
?>

Output
5
In the above example,
Use str_word_count( ) function is used to count the number of word in a string.
declare variable $str value="hello user how are you".
pass this function inside echo so the output is :5 (count words separated by space)

Eg vi ( strcmp( ) )

<?php
$str="hello";
$str1="HELLO";
echo strcmp($str,$str1);
?>

Output
1
In the above example,
declare two variable $str value=("hello")
$str1 with value=("HELLO")
Now compare two string using strcmp( ) function.
display the output i.e 1 because both variable doesn't contain same value(one is in lowercase
while other in uppercase).

Eg vii(strlen( ))

<?php

if(isset($_GET['sub']))

if(empty($_GET['n']))

echo "<font color='red'>fill your name first</font>";

else

if(strlen($_GET['n'])<5)
{

echo "<font color='red'>name must be greater than 5</font>";

else

echo "welcome ".$_GET['n'];

?>

<form>

Enter your name<input type="text" name="n"/>

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

</form>

Output
name must be greater than 5
Enter your name

Eg viii ( strpos( ) )

<?php

$str="welcome";

echo strpos($str,"l");

?>

Output
2

Eg ix ( nl2br( ) )

<?php

$str1="hello
user

how

are

you";

echo nl2br($str1);

?>

Output
hello
user
how
are
you

Eg x( substr( ) )

<?php

$str="welcome to the world of php";

echo substr($str,24,3);

?>

Output
php

In the above example,


substr( ) function is used to slice string into smaller section.
it accepts three argument: (given string ,the position at which start slicing , and the number
of character return from the starting position ).
$str hold a string value="welcome to the world of php" now pass substr($str,24,3) function
inside echo and the output will become: php

PHP empty() function


PHP empty() function checks whether a variable holds some value or not.

Eg
<?php

if(isset($_GET['sub']))

if(empty($_GET['n']))

echo "fill your name first";

else

echo "welcome ".$_GET['n'];

?>

<form>

Enter your name<input type="text" name="n"/>

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

</form>

Output welcome Rexx Enter your name

PHP str_split() Function


Splits a string into an array with the help of str_split() function. Syntax

str_split(string,length)

Example 1

<?php
$str="hello";
$array=str_split($str);
print_r($array);
?>
Output Array ( [0] => h [1] => e [2] => l [3] => l [4] => o )
Example 2(Passing Length Parameter)

<?php
$str="hello";
$array=str_split($str,2);
print_r($array);
?>

Output Array ( [0] => he [1] => ll [2] => o )

PHP numeric functions


Don't think that PHP's power is limited to strings only.

The language has over 50 built-in functions for working with numbers, ranging from simple
formatting functions to functions for arithmetic, logarithmic, and trigonometric
manipulations.

Sr. No Function What it Does


1 ceil() Rounds a number up
2 floor() Rounds a number down
3 abs() Finds the absolute value of anumber
4 pow() Raises one number to the power of another
5 exp() Finds the exponent of a number
6 rand() Generates a random number
7 bindec() Converts a number from binary to decimal
8 decbin() Converts a number from decimal to binary
9 decoct() Converts a number from decimal to octal
10 octdec() Converts a number from octal to decimal
11 dechex() Converts a number from decimal to hexadecimal
12 hexdec() Converts a number from hexadecimal to decimal
13 number_format() Formats number with grouped thousands and decimals
14 printf() Formats a number using a custom specification
15 round find round number
16 sqrt find square root of a number
Some of these important functions are

Eg i(ceil)
<?php

$num=19.7

echo ceil($num);

?>

Output 20
In the above example Initialize variable $num with value=19.7 , output will become 20.
because this function round value up.

Eg ii(floor)
<?php

$num=19.7

echo floor($num);

?>

Output 19
in the above example variable $num = 19.7,and the output will become 19. Because this
function round value down.

Eg iii(abs)
<?php

$num =-19.7

echo abs($num);

?>

Output 19
In the above example declare variable ($num) value=19.7 and the output will 19.7 Because
abs( ) returns the absolute of given number.

Eg iv(pow)
<?php

echo pow(4,3);

?>

Output 64
In the above example. Pass pow( ) function inside echo with value(4,3). Its multiply (value=4).
three times and the result is 64.

Eg v(rand)
<?php

echo rand(10,99);

?>

Output 55
In the above example Pass rand( ) function With value from( 10 to 99 ). it will display any
random value lies from 10 to 100. when we refresh the page on every refresh it show random
value like. 22,33 ,44,56 and so on.

Eg vi(bindec)
<?php

echo bindec(1000);

?>

Output 8
In the above example bindec( ) function pass inside echo statement with binary value = 1000.
So output will become 8 because bindec( ) function convert binary number into decimal
number.

Eg vii(decbin)
<?php

echo decbin(8);

?>

Output 1000
In the above example decbin( ) function Pass inside echo statement with decimal value = 8.
So output will become. 1000

Downlaod PHP, HTML, CSS, JS, CAKE Tutorial Pdf For


Beginners
PHP is a widely-used, open source scripting language used for scripts that are executed on
the server and it is freeware. It is a server side scripting language used to develop attractive
and dynamic web pages.

PHP is widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP.

For beginning use ( php tutorial pdf ) php tutorial pdf free download for beginners, php
book pdf, php tutorial pdf , php ebook free download and php tutorial for beginners with
examples.

We make available with database used with PHP is MYSQL – which is also an open source
which is an added advantage.

PHP’s simple programming style, we attempt to design in a way that enables anyone with
basic programming knowledge to learn and shift to never-ending opportunity available.

As mentioned above, our effort is focus on what You may desire to set up your own test
server, which is extremely unproblematic to do, using the next couple of chapters to help you
out.

Our center is to endow with you with uncomplicated information. If you already have a server
up and proceeding, or access to a server running PHP 5, you can skip to another sections,
php tutorial for learners with examples where we will trigger on writing some PHP Using To
go through all the chapters of step by step, in php tutorial pdf or you may jump between
chapters to study precise things - it's really up to you.

Php book pdf also available on the site. The new learners can take from php tutorial pdf free
download or php tutorial pdf free.

Our focal point is to present you with essential knowledge of HTML.

For this PHP download for beginners for the all functions and looping and all PHP tutorial
(pdf) and PHP ebook (free Download) from the site. Download Free Php Projects and
Download Free Php Projects for the users for the help to create projects.

php interview questions and answers pdf php interview questions and answers for freshers
are available for the Company Interview and preparation for the Corporative Training.
We provide you with the plenty of php tutorial pdf for the new and beginners, php book pdf
for beginners and professionals , php tutorial pdf free download for new students , php
tutorial pdf free download for the new kid on the block, php ebook free download, are
provided for the online study purpose.

Many PHP Projects are provided for the conceptualization of project developments under
Download Free Php Projects heading.

For professionals we have php interview questions and answers pdf, and php interview
questions and answers for freshers. By going through student are compatible with the terms
and functionality of PHP.

You might also like