UNIT-1
Unit 1
BUILDING BLOCKS OF PHP:-
PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
What is PHP
1. PHP stands for HyperTextPreprocessor.
2. PHP is an interpreted language, i.e. there is no need for compilation.
3. PHP is a server side scripting language.
4. PHP is faster than other scripting language e.g. asp and jsp.
PHP Features
1. Performance: Script written in PHP executes much faster then those scripts written in
other languages such as JSP & ASP.
2. Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying any
cost.
3. Platform Independent: PHP is available for WINDOWS, MAC, LINUX& UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
4. Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
5. Embedded: PHP code can be easily embedded within HTML tags and script.
Basic PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Let's see a simple PHP example where we are writing some text using PHP echo command.
<html>
<body>
<?php
echo "<h2>Hello First PHP</h2>";
?>
</body>
</html>
Echo and print are two commands to print data on to the screen.
1
UNIT-1
COMMENTS IN PHP
A comment in PHP code is a line that is not read/executed as part of the program.
we use // to make a single-line comment
/* */ to make a large comment block.
Example:
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
VARIABLE
A variable in PHP is a name of memory location that holds data. A variable is a temporary
storage that is used to store data temporarily. It hold values like number, string, object, array
or a Boolean.
In PHP, a variable is declared using $ sign followed by variable name.
Syntax of declaring a variable in PHP is given below:
$variablename=value;
Example:
$str=”php”;
$x=5;
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
PHP is a loosely typed language, it means PHP automatically converts the variable to its
correct data type.
CONSTANTS
Constant is a name or identifier that can't be changed during the execution of the script. PHP
constants can be defined in 2 ways:
1. Using define() function
syntax:define(name, value, case-insensitive)
1. name: specifies the constant name
2
UNIT-1
2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.
<?php
define("MESSAGE","Hello JavaTpoint PHP",true/false);
echo MESSAGE;
?>
2. Using const keyword
It is always case sensitive. It is faster that define( ).
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
DATA TYPES
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Helloworld!";
$y = 'Helloworld!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based
- prefixed with 0x) or octal (8-based - prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
3
UNIT-1
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
Example:
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
Example:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
4
UNIT-1
Variables can also be emptied by setting the value to NULL:
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
Reference to a third-party resource( a database, for example)
CHANGING TYPE WITH settype()
PHP also provides the function settype(), which is used to change the type of avariable.
settype($variabletochange, ‘new type’);
Example:
<?php
$x = 3.14;
echo “is “.$undecided.” a double? “.is_double($x).”<br/>”; // double
settype($x, ‘string’);
echo “is “.$x.” a string? “.is_string($x).”<br/>”; // string
settype($x, ‘integer’);
echo “is “.$undecided.” an integer? “.is_integer($x).”<br/>”; //
?>
CHANGING TYPE BY CASTING
The principal difference between using settype() to change the type of an existingvariable and
changing type by castingis the fact that casting produces a copy, leavingthe original variable
untouched. To change type through casting, you indicatethe name of a data type, in
parentheses, in front of the variable you are copying.
$newvar = (integer) $originalvar
Example:
<?php
$x = 3.14;
$holder = (double) $x;
echo “is “.$holder.” a double? “.is_double($holder).”<br/>”; // double
$holder = (string) $x;
echo “is “.$holder.” a string? “.is_string($holder).”<br/>”; // string
?>
OPERATORS AND EXPRESSIONS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
An expression is a sequence of operands and operators that reduces to a single value.
1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic
calculations.
Operator Description
+ Addition <?php
Subtraction $a=10;
* Multiplication $b=20;
echo $a+$b."<br>";
5 echo $b-$a."<br>";
echo $a*$b."<br>";
echo $b/$a."<br>";
echo $b%$a."<br>";
UNIT-1
/ Division
% Modulus (division remainder)
2. Comparison Operators: The comparison operators are used to compare two values
and gives either true (1) or false (0) result. The following are the comparison
operators. <?php
$a=10;
Operator Description $b=20;
== is equal to echo " a < b : " .($a < $b)."<br>";
!= is not equal echo "b > a :" .($b > $a)."<br>";
> is greater than echo " a!=b:" .($a != $b)."<br>";
< is less than echo "a==b:".($a==$b)."<br>";
>= is greater than or equal to echo "a <= b:".($a<=$b)."<br>";
<= is less than or equal to echo "a >= b:".($b>=$a)."<br>";
?>
3. Logical Operators: These are used to combine two or more comparison expression
and give the result either true or false. <?php
$a=10;
Operator Description
&& and $b=20;
|| Or echo ($a > 4) && ($a <33);
! Not ?>
4. Assignment Operators: Assignment operator is used to assign the result of an
expression to a variable.
V op=exp
5. Increment / Decrement Operator: The increment and decrement operator are unary
operators. <?php
The increment operator increases the value of an operand by 1. $a=10;
The decrement operator decreases the value of an operand by 1. $b=20;
Increment types are pre (++m) and post (m++) increment. echo "a++:".$a++."<br>";
Decrement types are pre (--m) and post (m--) decrement. echo "++a:".++$a."<br>";
echo "--b:".--$b."<br>";
echo "b--:".$b--."<br>";
echo "b--:".$b--."<br>";
?>
6. Concatenation operator: The concatenation operator is represented by a single
period (.). This operator appends the right-side operand to the left-side operand.
Example:
“ hello”. “ world”
It returns hello world
7. Conditional or Ternary Operator: The general form of conditional operator is as
follows:
Syntax: (Exp1)? Exp2:Exp3;
Working: Exp1 is evaluated first, if it is true, Exp2 will be executed. If Exp1 is false Exp3
will be executed.
6
UNIT-1
Example:
<?php
$x=10;
$y=23;
($x>$y)?print " $x is larger" : print "$y is larger";
?>
FLOW CONTROL FUNCTIONS IN PHP:-
SWITCHING FLOW
It is common for scripts to evaluate conditions and change their behavior accordingly. These
decisions are what make your PHP pages dynamic—that is, able to change output according
to circumstances. Like most programming languages, PHP enables you to do this with an if
statement.
Example:
If statement: <?php
Syntax: if (expression) { $mood = “happy”;
// statement-block if ($mood == “happy”) {
} echo “Hooray! I’m in a good
mood!”;
If this expression results in a true value, the statement is executed. }
Otherwise, the statement is skipped entirely. ?>
Example:
If..Else Statement:
<?php
Syntax:if (expression) {
$mood = “sad”;
// True block statement(s)
if ($mood == “happy”) {
} else {
echo “Hooray! I’m in a good
// False-block statement(s)
mood!”;
}
} else {
If the expression is true, the true block statement(s) are executed. echo “I’m in a $mood mood.”;
Otherwise, the false-block statement(s) are executed. }
?>
The ElseIf Statement
Syntax: if (expression) {
// statement-1
Example:
} elseif (another expression) {
// statement-2 <?php
} else { $mood = “sad”;
// default-statement if ($mood == “happy”) {
} echo “Hooray! I’m in a good mood!”;
} elseif ($mood == “sad”) {
The expressions are evaluated from top downwards. echo “Awww. Don’t be down!”;
As soon as the true condition is found, the statement } else {
associated with it is executed. Otherwise, the final else echo “I’m neither happy nor sad, but
$mood.”;
statement will be executed.
}
?>
The switch statement:
Syntax:switch (expression) {
casecase1:
7
UNIT-1
// execute this if expression results in result1
break;
casecase2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
The switch statement tests the value of a given expression against a list of case values and
when a match is found, a block of statements associated with that case is executed.
Example:
<?php
$x = “sad”;
switch ($x) {
case “happy”:
echo “Hooray! I’m in a good mood!”;
break;
case “sad”:
echo “Awww. Don’t be down!”;
break;
default:
echo “I’m neither happy nor sad, but $mood.”;
break;
}
?>
LOOPS
The process of repeatedly executing a block of statements is known as Looping.
Looping statements
1. While Loop:
Syntax:
while(condition){
//code to be executed
}
The control loops through a block of code if and as long as a specified condition is true.
Example:
<?php
$x=1;
$sum=0;
while($x<10)
{
$sum=$sum+$x;
$x++;
}
print " The sum of natural number is ".$sum;
?>
2. Do..While:
Syntax:
do{
//code to be executed
8
UNIT-1
}while(condition);
Loops through a block of code once, and then repeats the loop as long as a special condition
is true.
Example:
<?php
$x=1;
$sum=0;
do
{
$sum=$sum+$x;
$x++;
}
while($x<10);
print " The sum of natural number is ".$sum;
?>
3. For statement:
Syntax:
for(initialization; condition; increment/decrement){
//code to be executed
}
Execution of the for statement is as follows
1. Initialization of the control variable is done first.
2. The value of the control variable is tested using the test condition. When the loop is
true, the body of the loop is executed. Otherwise the loop is terminated.
3. When the body of the loop is executed, the control is transferred back to thefor
statement after evaluating the last statement in the loop. Now the control variable is
incremented or decremented. The new value of the control variable is tested again to
see whether it satisfies the loop condition. If the condition is satisfied, the body of the
loop is again executed. This process continues till the value of the control variable
fails to satisfy the test condition.
Example:
<?php
$x;
$sum=0;
for($x=1;$x<10;$x++)
{
$sum=$sum+$x;
}
print " The sum of natural number is ".$sum;
?>
Difference b/w while and do-while:
While Do -while
It is an entry-control loop it is an exit-controlled loop
Test condition is tested first Test condition is tested after executing the
body of the loop
9
UNIT-1
It is pre-testing loop It is post-testing loop
It will not give guarantee to execute the body It will give the guarantee to execute the body
of the loop minimum once of the loop minimum once
Syntax: while (condition) Syntax: do
Simple or compound statement; Simple (or) compound statement;
while(condition);
BREAK STATEMENT:
The break statement is used to terminate the loop. When the breakstatement is encountered
inside a loop, the loop is immediately exited and the program continues with the statement
immediately following the loop. When the loops are nested, the break would only exit from
the loop containing it. That is, the break will exit only a single loop.
Syntax: break;
Example:
<?php
$i;$sum=0;$n=10;
for($i=1;$i<=$n;$i++)
{
if($i==6)
break;
$sum=$sum+$i;
}
print " The sum is " .$sum;
?>
CONTINUE STATEMENT:
The continue statement tells the compiler. “SKIP THE FOLLOWING STATEMENTS AND
CONTIUNE WITH THE NEXT ITERATION”. The format of the continue statement is
simply
Syntax: continue;
Example:
<?php
$i;$sum=0;$n=10;
for($i=1;$i<=$n;$i++)
{
if($i==6)
continue;
$sum=$sum+$i;
}
print " The sum is " .$sum;
?>
10
UNIT-1
Nested Loops:
Nesting of loops, that is, one for statement within another forstatement.
Example:
<?php
$row;
$col;
echo "<table border='1'>";
for($row=1;$row<=10;$row++)
{
echo "<tr>";
for($col=1;$col<=10;$col++)
{
echo "<td>".($row*$col);
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
CODE BLOCKS AND BROWSER OUTPUT
Imagine a script that outputs a table of values only when a variable is set to the Boolean
value true.A simplified HTML table constructed with the code block of an ifstatement.
A Code Block Containing Multiple print() Statements
<?php
$display_prices = true;
if ( $display_prices ) {
print "<table border=\"1\">";
print "<tr><td colspan=\"3\">";
print "today's prices in dollars";
print "</td></tr>";
print "<tr><td>14</td><td>32</td><td>71</td></tr>";
print "</table>";
}
?>
We can return to HTML mode within a code block. By this we can save ourselves some
typing. We avoided using print statement.
<?php
$display_prices = true;
if ( $display_prices ) {
?>
<table border="1">
<tr><td colspan="3">today's prices in dollars</td></tr>
<tr><td>14</td><td>32</td><td>71</td>
</table>
<?php
}
?>
WORKING WITH FUNCTIONS:-
Function:A functions is a block of code to perform task. Functions are different types like
built-in functions and user defined functions. We have hundreds of built-in functions in PHP.
11
UNIT-1
User defined functions are functions which are defined by user.
By using functions we can easily understand the program easy, and we can test and debug the
program easy.
Syntax:functionfunction_name(arguments/parameterlist)
Example for built-in function
<?php Example for user defined function
$num = -321; <?php
$newnum = abs($num); function test($x)
echo $newnum; {
?> echo $x;
}
test("hello world");
Function Definition (or) called function: ?>
Syntax:
functionfunction_name(parameter-list)
{
Local variable declarations;
Executable statement1;
Executable statement2; function body
…………..
Return statement;
}
It contains the actual coding of the function.
Function_name specifies the name of the function.
Parameter-listdeclares variables that will receive the data sent by calling program.
Function body contains the declarations and statements necessary for performing the required
task. The body is enclosed with curly braces { }.
Function Call or calling function:
A function can be called by simply using the function name followed by a list of actual
parameters, if any, enclosed in parentheses.
Whenever a function is called, the execution control is transferred to that function. After
completion of function execution, the control returns to the calling point.
The general form of calling a function is as follows:
function_name(argument-list);
Example;
sum(10,29);
square(2);
Return Statement:(Return values and their Types)
The return statement is used to return a value from a user-defined function to its calling
point. The statement can be used in the following ways.
Syntax-1: return;
Syntax-2: return (value);
Examples:
1.return;
2. return (25);
12
UNIT-1
3. return (x+y);
4. return x+y;
There are two types of parameters. They are
(i) Actual Parameters and
(ii) Formal parameters.
Actual Parameters: The parameters that are included in function calling point are called
“actual parameters”. These are used to send vales to the called function.
Formal Parameters: The parameters that are included in function definition are called
“formal parameters”. These are used to receive values from the calling point.
While using actual and formal parameters the following rules must be followed:
1. The number of actual parameters must be equal to the number of formal parameters.
VARIABLE SCOPE
In PHP, variables can be declared anywhere in the script.
PHP has three different variable scopes:
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function.
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function.
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
13
UNIT-1
myTest();
echo $y; // outputs 15
?>
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Example: CALL-BY-VALUE:
<?php
function text($x) In this method, actual arguments of function call are passed to the formal
{ parameters of the called function. Inside the function, the value of formal
echo $x; parameters changes according to the need. When the control is returned to
}
functionmul($x,$y) its calling point, the changed values of formal parameters are not
{ transferred. This type of passing technique is called call-by-value
return ($x*$y); mechanism.
}
function add() (Or)
{ In case of PHP call by value, actual value is not modified if it is modified
$x=10; inside the function.
$y=20; <?php
return ($x+$y);
} functionaddFive($num)
function test() {
{ $num += 5;
$x=10; }
echo "hello"."<br>"; $orignum = 10;
echo $x; addFive($orignum);
}
text(" ashwikareddy"); echo $orignum;
echo "<br>"; ?>
$a=mul(13,2);
echo $a."<br>";
$b=add();
echo $b."<br>";
test();
?>
14
UNIT-1
CALL-BY-REFERENCE
In case of PHP call by reference, actual value is modified if it is modified inside the function. In
such case, you need to use & (ampersand) symbol with formal arguments. The & represents
reference of the variable.
<?php
functionaddFive(&$num)
{
$num += 5;
}
$orignum = 10;
addFive($orignum);
echo $orignum;
?>
15