PHP Introduction
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.
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 !.
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).
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.
Step:8 choose your browser asked if firefox found click on yes otherwise no
Step:9 Completing the setup wizard click on finish
<?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
click OK.
Click on Install.
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
<?php
?>
<?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.
<?
?>
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
<script language="PHP">
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.
Or backslash(//)
<?php
?>
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..
<?php
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
/*
*/
?>
The all lines which is define in php evironment are Multiline comments. it is non-
executable.Because it enlose with Multiline comments statement.
<?php
/*
*/
?>
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.
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 _ )
This assign value on the right side of the equation to the variable on the left.
Eg i
<?php
$myCar = "Honda";
echo $myCar;
?>
Output Honda
PHP Concatenation
Eg ii (concatenate variable with string)
<?php
?>
<?php
$first = 100;
$second = 200;
?>
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.
<?php
$first = 1000;
$second = 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.
Eg v
<?php
$name="steve";
echo $name;
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;
unset($third);
?>
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.
<?php
$name="rexx";
$NAME="rahul";
echo $name."<br/>";
echo $NAME;
?>
Variable names in PHP are case-sensitive. As a result, $name refers to a different variable than
does $NAME.
<?php
//define variables
$name = "Fiona";
$age=25;
var_dump ($name);
var_dump($age);
?>
<?php
$first = 100;
$second = 200;
var_dump ($third);
?>
<?php
$first = 100.5;
$second = 200.2;
var_dump ($third);
?>
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
<?php
$bool = true;
var_dump ($bool);
?>
In the above variable $bool with value="true". var_dump($bool) function is used to display
the result so output will display Boolean true, because variable holds a Boolean value
<?php
$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
When you set $x to a value, it will replace that variable name with the value of the
variable you provide.
$$x(reference variable) hold value = 200. now we want to print the value.
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/>";
?>
<?php
$name="Ravi";
${$name}="Ranjan";
${${$name}}="Rexx";
echo $name;
echo ${$name};
echo ${${$name}};
?>
Output
Ravi
Ranjan
Rexx
variable ${$ {$name} } hold value ="Rexx" // it act as "variable's of variable of variable"
reference.
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"]
$_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"]
Eg
$_SERVER["SERVER_PORT"]
$_SERVER["SERVER_NAME"]
$_SERVER["REQUEST_URI"]
//third is blank
$z=0;
//again store $z in $y
$y=$z;
<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>
<?php
//swap two numbers without using third variable
$x=20;
$y=10;
?>
<?php
$a = 10;
$b = 20;
?>
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.
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');
?>
<?php
define('SUM 2',ONE+TWO);
define('@SUM',ONE+TWO);
?>
<?php
define('NAME', "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
<?php
define('ONE', 100);
define('TWO', 100);
define('SUM',ONE+TWO);
?>
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);
?>
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.
<?php
define('ONE', 100);
define('TWO', 100);
$res= ONE+TWO;
?>
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.
<?php
//define exchange rate
//1.00 USD= 0.80 EUR
define('EXCHANGE_RATE',0.80);
?>
Output
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.
__LINE__
The current line number of the file.
<?php
?>
__FILE__
The full path and filename of the file.
<?php
?>
<?php
class demo
function test()
function testme()
$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
?>
PHP_INT_MAX
The PHP integer value limit
<?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.
<?php
$name = "John";
$profile = "PHP Developer";
$age = 25;
echo $name , $profile , $age, " 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
<?php
$name = "John";
$ret = echo $name;
?>
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" .
<?php
$name = "John";
$profile = "PHP Developer";
$age = 25;
print $name , $profile , $age, " years old";
?>
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 .
<?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
$num=100;
$fnum=100.0;
$str="Hello";
var_dump($num,$fnum,$str);
?>
1. Scalar(predefined)
2. Compound(user-defined)
3. Special type
1. Integer
2. Float/double
3. String
4. Boolean
Integer means numeric data types. A whole number with no fractional component.
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:
<?php
$num=100.0;
var_dump($num);
?>
Output float(100)
$num hold value=100.0. pass $num inside echo statement to display the output.
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);
?>
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 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);
?>
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)
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
<?php
class Demo
//$obj->show();
//$obj->show();
var_dump($obj);
?>
1. Null
2. Resource
<?php
$blank=null;
var_dump($blank);
?>
Output NULL
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.
<?php
$x = 1000;
$y = 500;
$sum = $x + $y;
else
?>
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.
HTML Form
Save it as Choose.php
<html>
<head>
<title>form method</title>
</head>
<body>
<form method="post">
<tr>
<td>
<Selct name="selType">
</select>
</td>
</tr>
<tr>
<td>Color:</td>
</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'];
?>
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!
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.
<html>
<head>
<?php
echo $_GET['n'];
?>
<title>get_browser</title></head>
<form method="GET">
<tr>
</tr>
<tr>
</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.
<html>
<head>
<title>get_browser</title>
<?php
error_reporting(1);
$x=$_GET['f'];
$y=$_GET['s'];
$z=$x+$y;
?>
</head>
<tr>
</tr>
<tr>
</tr>
<tr align="center">
</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.
<html>
<head>
<?php
echo $_POST['n'];
?>
<title>get_browser</title>
</head>
<form method="post">
<tr>
</tr>
<tr>
</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;
?>
</head>
<tr>
</tr>
<tr>
</tr>
<tr align="center">
</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.
<?php
error_reporting(1);
$id = $_POST['id'];
$pass = $_POST['pass'];
if(isset($_POST['signin']))
header('location:https://www.phptpoint.com');
else
?>
<body>
<form method="post">
</td>
</tr>
<tr>
</td>
</tr>
<tr>
</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.
<body>
<tr>
</tr>
<tr>
</td>
</tr>
</table>
</form>
</body>
PHP Script
Save it as Logic.php
<?php
$name=$_POST['n'];
?>
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>
</head>
<tr>
</tr>
<tr>
</tr>
<tr>
</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">
</tr>
</table>
</form>
</body>
</html>
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
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.
<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
Output.php
Output
Your Email is
Your Password is
Your Address is
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.
extract($_POST);
<html>
<head>
</head>
<body>
<form method="post">
<Tr>
<th>Result</th>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</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 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.
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
The use of some common arithmetic operators is here illustrated by an example as follows:-
<?php
$x=10;
$y=5;
//addition
$sum=$x+$y;
echo "sum=".$sum."<br/>";
?>
Output sum = 15
<?php
$x=10;
$y=5;
//subtraction
$sub=$x-$y;
echo "sub=".$sub."<br/>";
?>
Output sub = 5
<?php
$x=10;
$y=5;
//Multiply
$multiply=$x*$y;
?>
Output Multiplication = 50
<?php
$x=10;
$y=5;
//quotient
$div=$x/$y;
?>
Output Div = 2
<?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).
<?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).
<?php
$x = 1000;
$x-= 500;
?>
<?php
$x = 100;
$x*= 10;
?>
<?php
$x = 1000;
$x/= 500;
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).
<?php
$x = 5;
$x%= 2;
?>
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
<?php
echo $str."<br/>";
?>
== Equal to
!= Not equal
> Greater th
$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 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
<?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.
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";
header('location:https://www.phptpoint.com');
else
?>
OR(||) Operator
Operator name or pass
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
?>
Not(!) Operator
Operator not
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)
else
?>
<?php
if(isset($_GET['login']))
$eid=$_GET['e'];
$pass=$_GET['p'];
if($eid=="" || $pass=="")
else
else
?>
<form>
</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.
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.
<?php
echo (((4*8)-2)/10);
echo (4*8-2/10);
?>
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.
If Statement works much like the English language statement, "if X happens, then do Y."
<?php
if(isset($_GET['save']))
if($_GET['n']%2==0)
?>
<body>
<form method="get">
</form>
</body>
Output
10 is even number
Enter Your number
<?php
$num=$_POST['n'];
if($num>0)
?>
<body>
<form method="post">
</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
<?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.
But if-else statements allows you to display output in both the condition(if condition is true
display some message otherwise display other message).
<?php
$num=$_POST['n'];
if($num>0)
else
?>
<body>
<form method="post">
</form>
</body>
Output
-10 is negative number
Enter your number
<?php
$num=$_POST['n'];
if($num%2==0)
else
?>
<body>
<form method="post">
<input type="submit"/>
</form>
</body>
Output
1 is odd number
Enter your number
<?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
<?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
?>
<body>
<form method="post">
<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
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)
else if ($i == 1)
else if ($i == 2)
//using switch
switch ($i)
case 0:
case 1:
break;
case 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.
same for switch($i) matched the case 2: so the output will : 2 equals 2.
<?php
$i=0;
switch ($i)
case 0:
case 1:
case 2:
}
?>
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).
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:
break;
case 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.
<?php
$i=5;
switch ($i)
case 0:
break;
case 1:
break;
case 2:
break;
default:
?>
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:
?>
<form method="post">
Enter first number<input type="text" name="f"/><hr/>
</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
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>
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>
OR
When you want to execute same statements more than one times then use loop.
code to be executed;
{
echo "The Number is: ".$i."<br/>";
?>
<?php
$name="rexx";
?>
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)
<?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
<?php
?>
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)
<?php
{
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.
<?php
if($i%2==0)
@$even=$even+$i;
else
@$odd=$odd+$i;
?>
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.
<?php
@$f=$_GET['f'];
@$s=$_GET['s'];
$f++;
?>
<body>
<form>
</form>
</body>
Output
Sum of given numbers=1000
Enter first number
Enter Second number
<?php
@$f=$_GET['f'];
@$s=$_GET['s'];
$f--;
?>
<html>
<body>
<form>
</form>
<body>
Output
Subtraction of given numbers=500
Enter first number
Enter Second number
<?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
if(isset($_POST['create']))
$rows=$_POST['r'];
$cols=$_POST['c'];
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">
<tr>
</tr>
<tr>
</tr>
<tr>
<td colspan="2">
</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 (condition)
code to be executed;
Eg
<?php
$i=1;
while($i<=5)
$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.
<?php
$i=1;
$sum=0;
while($i<=100)
{
$sum=$sum+$i;
$i++;
?>
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
<?php
@$num=$_GET['num'];
$sum=0;
$rem=0;
$len=0;
while((int)$num!=0)
$len++;
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
?>
<body>
<form>
</form>
</body>
Output
Length of given digit= 5
Sum of given digit= 15
Enter first number
Syntax
do
{
code to be executed;
}
while (condition);
Eg
<?php
$i=1;
do
$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.
<?php
@$tab=$_GET['tab'];
$i=1;
do
$t=$tab*$i;
$i++;
while ($i<=10);
?>
<body>
<form>
</form>
</body>
Output
10 20 30 40 50 60 70 80 90 100
Enter your table
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);
?>
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");
{
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.
<?php
$color=array("r"=>"red", "g"=>"green","b"=>"black","w"=>"white");
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.
<?php
$array=array(10,11,12,13,14,15);
$sum=0;
$sum=$sum+$x;
?>
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.
Sr Function Wha
1 empty() Tests if a string is empty
Eg ii ( strrev( ) )
<?php
$val="nitin";
if(strrev($val)==$val)
else
?>
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
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']))
else
if(strlen($_GET['n'])<5)
{
else
?>
<form>
</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
echo substr($str,24,3);
?>
Output
php
Eg
<?php
if(isset($_GET['sub']))
if(empty($_GET['n']))
else
?>
<form>
</form>
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);
?>
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.
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
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.
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.