PHP Unit 1
PHP Unit 1
Contents
What Does PHP Do? ............................................................................................................... 1
A brief history of PHP ............................................................................................................. 1
Lexical Structure ..................................................................................................................... 2
Case Sensitivity ................................................................................................................... 2
Statements and Semicolons ............................................................................................... 2
Whitespace and Line Breaks ............................................................................................... 2
Comments........................................................................................................................... 3
Literals ................................................................................................................................ 4
Identifiers............................................................................................................................ 4
Variable names ................................................................................................................... 4
Function names .................................................................................................................. 4
Class names ........................................................................................................................ 4
Constants ............................................................................................................................ 5
Keywords ............................................................................................................................ 5
PHP Data Types ...................................................................................................................... 5
PHP String ........................................................................................................................... 6
PHP Integer ......................................................................................................................... 6
PHP Float............................................................................................................................. 6
PHP Boolean ....................................................................................................................... 6
PHP Array ............................................................................................................................ 7
PHP object .......................................................................................................................... 7
PHP Null .............................................................................................................................. 7
PHP Resource...................................................................................................................... 7
Variables ................................................................................................................................. 8
Variable Variables ............................................................................................................... 8
Variable References ............................................................................................................ 8
Expressions and Operators .................................................................................................... 9
Operator Associativity ........................................................................................................ 9
Implicit Casting ................................................................................................................... 9
PHP Operators ........................................................................................................................ 9
PHP Arithmetic Operators .................................................................................................. 9
PHP Assignment Operators .............................................................................................. 10
PHP Unit 1 2 GSC BCA
Server-side scripting
PHP was originally designed to create dynamic web content, and it is still best suited for
that task. To generate HTML, you need the PHP parser and a web server through which
to send the coded documents. PHP has also become popular for generating XML
documents, graphics, Flash animations, PDF files, and so much more.
Command-line scripting
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You
might use the command-line scripts for system administration tasks, such as backup
and log parsing; even some CRON job type scripts can be done this way (nonvisual PHP
tasks).
PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Early non-released
versions were used on his home page to keep track of who was looking at his online
resume. The first version used by others was available sometime in early 1995 and was
known as the Personal Home Page Tools. The parser was rewritten in mid-1995 and
named PHP/FI Version 2. The FI came from another package Rasmus had written which
interpreted html form data. He combined the Personal Home Page tools scripts with the
Form Interpreter and added mSQL support and PHP/FI was born. PHP/FI grew at an
amazing pace and people started contributing code to it.
It is estimated that by late 1996 PHP/FI was in use on at least 15,000 web sites around
the world. By mid-1997 this number had grown to over 50,000. Mid-1997 also saw a
change in the development of PHP. The parser was rewritten from scratch by Zeev
Suraski and Andi Gutmans and this new parser formed the basis for PHP Version 3. A lot
of the utility code from PHP/FI was ported over to PHP3 and a lot of it was completely
rewritten.
Today (end-1999) either PHP/FI or PHP3 ships with a number of commercial products
such as C2's StrongHold web server and RedHat Linux. A conservative estimate based
on an extrapolation from numbers provided by NetCraft would be that PHP is in use on
over 1,000,000 sites around the world.
PHP Unit 1 2 GSC BCA
Lexical Structure
The lexical structure of a programming language is the set of basic rules that governs
how you write programs in that language. It is the lowest-level syntax of the language
and specifies such things as what variable names look like, what characters are used for
comments, and how program statements are separated from each other.
Case Sensitivity
The names of user-defined classes and functions, as well as built-in constructs
and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three
lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and
$NaME are three different variables.
Comments
Comments give information to people who read your code, but they are ignored
by PHP at execution time.
PHP provides several ways to include comments within your code as -
Shell-style comments
When PHP encounters a hash mark character (#) within the code, everything
from the hash mark to the end of the line or the end of the section of PHP code
(whichever comes first) is considered a comment. This method of commenting is found
in Unix shell scripting languages and is useful for annotating single lines of code or
making short notes.
Because the hash mark is visible on the page, shell-style comments are
sometimes used to mark off blocks of code:
#######################
## Cookie functions
#######################
Sometimes they’re used before a line of code to identify what that code does, in which
case they’re usually indented to the same level as the code:
if ($doubleCheck) {
# create an HTML form requesting that the user confirm the action
echo confirmationForm();
}
C++ comments
When PHP encounters two slashes (//) within the code, everything from the
slashes to the end of the line or the end of the section of code, whichever comes first, is
considered a comment. This method of commenting is derived from C++. The result is
the same as the shell comment style.
Here are the shell-style comment examples, rewritten to use C++ comments:
////////////////////////
// Cookie functions
////////////////////////
if ($doubleCheck) {
// create an HTML form requesting that the user confirm the
action
echo confirmationForm();
}
C comments
When PHP encounters a slash followed by an asterisk (/*), everything after that,
until it encounters an asterisk followed by a slash (*/), is considered a comment. This
kind of comment can span multiple lines.
Literals
A literal is a data value that appears directly in a program. The following are all
literals in PHP:
Identifiers
Variable names
Variable names always begin with a dollar sign ($) and are case-sensitive. Here
are some valid variable names:
$bill $MaximumForce $_underscore
$head_count $I_HEART_PHP $_int
Function names
Function names are not case-sensitive. Here are some valid function names:
tally LOWERCASE_IS_FOR_WIMPS
list_all_users _hide
deleteTclFiles
These function names refer to the same function:
Howdy HoWdY HOWDY HOWdy howdy
Class names
Class names follow the standard rules for PHP identifiers and are also not case-
sensitive.
PHP Unit 1 5 GSC BCA
Keywords
A keyword (or reserved word) is a word set aside by the language for its core
functionality—you cannot give a variable, function, class, or constant the same name as
a keyword. Table 2-1 lists the keywords in PHP, which are case-insensitive.
Variables can store data of different types, and different data types can do different
things.
1. String 5. Array
2. Integer 6. Object
3. Float 7. NULL
4. Boolean 8. Resource
PHP Unit 1 6 GSC BCA
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:
Output:
<?php
$x = "Hello world!"; Hello world!
$y = 'Hello world!'; Hello world!
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.
In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
<?php Output:
$dec1 = 34;
$oct1 = 0243; Decimal number: 34
$hexa1 = 0x45; Octal number: 163
echo "Decimal number: " .$dec1. "</br>"; HexaDecimal number:
echo "Octal number: " .$oct1. "</br>"; 69
echo "HexaDecimal number: " .$hexa1. "</br
>";
?>
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can
hold numbers with a fractional or decimal point, including a negative or positive sign.
<?php Output:
$n1 = 19.34;
$n2 = 54.472; Result: 73.812
$sum = $n1 + $n2;
echo "Result: " .$sum;
?>
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values:
TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition is
correct, it returns TRUE otherwise FALSE.
PHP Unit 1 7 GSC BCA
<?php Output:
if (TRUE)
echo "This condition is TRUE."; This condition is
if (FALSE) TRUE.
echo "This condition is FALSE.";
?>
PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.
<?php Output:
$bikes = array("Suzuki", "Yamaha", "KTM");
echo "Element1: $bikes[0] </br>"; Element1: Suzuki
echo "Element2: $bikes[1] </br>"; Element2: Yamaha
echo "Element3: $bikes[2] </br>"; Element3: KTM
?>
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
<?php Output:
class bike {
function model() { Bike Model: Yamaha
$model_name = "Yamaha";
echo "Bike Model: "
.$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive. The special type of data type NULL
defined a variable with no value.
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources.
PHP Unit 1 8 GSC BCA
Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here,
some important points to know about variables:
1. As PHP is a loosely typed language, so we do not need to declare the data types of
the variables.
2. After declaring a variable, it can be reused throughout the code.
3. Assignment Operator (=) is used to assign the value to a variable.
1. A variable must start with a dollar ($) sign, followed by the variable name.
2. It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
3. A variable name must start with a letter or underscore (_) character.
4. A PHP variable name cannot contain spaces.
5. Variable name cannot start with a number or special symbols.
6. PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
<?php Output:
$str="hello string";
$x=200; string is: hello
$y=44.6; string
echo "string is: $str <br/>"; integer is: 200
echo "integer is: $x <br/>"; float is: 44.6
echo "float is: $y <br/>";
?>
Variable Variables
You can reference the value of a variable whose name is stored in another
variable by prefacing the variable reference with an additional dollar sign ($). For
example:
$foo = "bar";
$$foo = "baz";
After the second statement executes, the variable $bar has the value "baz".
Variable References
In PHP, references are how you create variable aliases. To make $black an alias
for the variable $white, use:
$black =& $white;
PHP Unit 1 9 GSC BCA
Operator Associativity
Associativity defines the order in which operators with the same order of
precedence are evaluated.
Implicit Casting
PHP’s variables can store integers, floating-point numbers, strings, and more,
and to keep as much of the type details away from the programmer as possible, PHP
converts values from one type to another as necessary.
The conversion of a value from one type to another is called casting. This kind of
implicit casting is called type juggling in PHP.
PHP Operators
Operators are used to perform operations on variables and values. PHP divides the
operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators
8. Conditional assignment operators
Same
Assignment Description
as...
The left operand gets set to the value of the expression on the
x=y x=y
right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
=== Identical $x === Returns true if $x is equal to $y, and they are of
$y the same type
!== Not identical $x !== Returns true if $x is not equal to $y, or they are
$y not of the same type
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater
$y than zero, depending on if $x is less than, equal
to, or greater than $y. Introduced in PHP 7.
=== Identity $x === Returns true if $x and $y have the same key/value
$y pairs in the same order and of the same types
Flow-Control Statements
Conditional statements, such as if/else and switch, allow a program to execute
different pieces of code, or none at all, depending on some condition. Loops, such as
while and for, support the repeated execution of particular segments of code.
1. Conditional statements
a. if statement - executes some code if one condition is true
b. if...else statement - executes some code if a condition is true and another
code if that condition is false
c. if...elseif...else statement - executes different codes for more than two
conditions
d. switch statement - selects one of many blocks of code to be executed
2. Loop
a. while - loops through a block of code as long as the specified condition is
true
b. do...while - loops through a block of code once, and then repeats the loop
as long as the specified condition is true
c. for - loops through a block of code a specified number of times
d. foreach - loops through a block of code for each element in an array
Conditional Statement
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
if(condition){
//code to be executed
}
Example
<?php Output:
$num=12;
if($num<100){ 12 is less than 100
echo "$num is less than
100";
}
?>
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false. It executes one
block of code if the specified condition is true and another block of code if the condition
is false.
Syntax
if(condition){
PHP Unit 1 14 GSC BCA
<?php Output:
$num=12;
if($num%2==0){ 12 is even number
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
PHP Unit 1 15 GSC BCA
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
Output:
B Grade
Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Example
<?php Output:
$age = 23;
$nationality = "Indian"; Eligible to give
//applying conditions on nationality and vote
age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions.
It works like PHP if-else-if statement.
Syntax
PHP Unit 1 16 GSC BCA
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the values for
each case in the structure. If there is a match, the block of code associated with that case
is executed. Use break to prevent the code from running into the next case
automatically. The default statement is used if no match is found.
Example
<?php Output:
$num=20;
switch($num){ number is equal to
case 10: 20
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Loops
Syntax
while(condition){
//code to be executed
PHP Unit 1 17 GSC BCA
Example 1
<?php Output:
$n=1;
while($n<=5){ 1
echo "$n<br/>"; 2
$n++; 3
} 4
?> 5
Example 2 – printing alphabets using while loop.
<?php Output:
$i = 'A';
while ($i < 'F') { A
echo $i; B
$i++; C
echo "</br>"; D
} E
?>
Syntax
do{
//code to be executed
}while(condition);
Example
<?php Output:
$n=1; 1
do{ 2
echo "$n<br/>"; 3
$n++; 4
}while($n<=5); 5
?>
PHP Unit 1 18 GSC BCA
The while loop is also named as entry The do-while loop is also named as exit
control loop. control loop.
The body of the loop does not execute if The body of the loop executes at least once,
the condition is false. even if the condition is false.
Condition checks first, and then block of Block of statements executes first and then
statements executes. condition checks.
Syntax
initialization - Initialize the loop counter value. The initial value of the for loop is done
only once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise the execution of the
loop ends.
Example 1
<?php Output:
for($i=1;$i<=3;$i++){
echo "$n<br/>"; 1
} 2
?> 3
Example 2
All three parameters are optional, but semicolon (;) is must to pass in for loop. If
we don't pass parameters, it will execute infinite.
<?php
$i = 1;
//infinite loop
for (;;) {
PHP Unit 1 19 GSC BCA
echo $i++;
echo "</br>";
}
?>
Output:
1
2
3
.
.
In case of inner or nested for loop, nested for loop is executed fully for one outer for
loop. If outer for loop is to be executed for 3 times and inner for loop for 3 times, inner
for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop
and 3 times for 3rd outer loop).
Example
<?php Output:
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){ 1 1
echo "$i $j<br/>"; 1 2
} 1 3
} 2 1
?> 2 2
2 3
3 1
3 2
3 3
Syntax
foreach ($array as $value) {
//code to be executed
}
<?php Output:
//declare array
$season = array ("Summer", "Winter", Summer
"Autumn", "Rainy"); Winter
Autumn
//access array elements using foreach loop Rainy
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
PHP try-catch
PHP try and catch are the blocks with the feature of exception handling, which
contain the code to handle exceptions. They play an important role in exception
handling. There is one more important keyword used with the try-catch block is throw.
The throw is a keyword that is used to throw an exception.
Each try block must have at least one catch block. On the other hand, a try block
can also have multiple catch blocks to handle various classes of exception.
Syntax
The following syntax is used in exception handling to handle runtime errors -
<?php
//try block
try {
//code that can throw exception
}
//catch block
catch (Exception $e) {
//code to print exception caught in the block
}
//finally block
finally {
//any code that will always execute
}
?>
try
The try block contains the code that may contain an exception. An exception
raised in try block during runtime is caught by the catch block. Therefore, each try block
must have at least one catch block. It consists of the block of code in which an exception
can occur.
catch
The catch block catches the exception raised in the try block. It contains the code
to catch the exception, which is thrown by throw keyword in the try block. The catch
block executes when a specific exception is thrown. PHP looks for the matching catch
block and assigns the exception object to a variable.
throw
It is a keyword, which is used to throw an exception. Note that one throw at least
has one "catch block" to catch the exception. It lists the exceptions thrown by function,
which cannot be handled by the function itself.
finally
It is a block that contains the essential code of the program to execute. The finally
block is also used for clean-up activity in PHP. It is similar to the catch block, which is
used to handle exception. The only difference is that it always executes whether an
exception is handled or not.
The finally block can be specified after or in place of catch block. It always
executes just after the try and catch block whether an exception has been thrown or not,
and before the normal execution restarts. It is useful in the following scenarios - Closing
of database connection, stream.
Example 1
<?php
//user-defined function with an exception
function checkNumber($num) {
if($num>=1) {
//throw an exception
throw new Exception("Value must be less than 1");
}
return true;
}
//catch exception
catch (Exception $e) {
PHP Unit 1 22 GSC BCA
Output:
Declare
The declare keyword sets an execution directive for a block of code. If the declare
statement is not followed by a block then the directive applies to the rest of the code in
the file.
There are three directives which can be declared: ticks, encoding and strict_types.
Syntax
exit(message)
<?php
$site = "https://www.w3schools.com/";
fopen($site,"r")
or exit("Unable to connect to $site");
?>
The return statement returns from a function or, at the top level of the program, from
the script.
<?php Output:
function add1($x) { 5 + 1 is 6
return $x + 1;
}
echo "5 + 1 is " .
add1(5);
?>
PHP Unit 1 23 GSC BCA
Goto
The goto operator can be used to jump to another section in the program. The
target point is specified by a case-sensitive label followed by a colon, and the instruction
is given as goto followed by the desired target label.
Example 1
<?php Output:
goto a;
echo 'Foo'; Bar
a:
echo 'Bar';
?>
PHP allows you to include file so that a page content can be reused many times. It is
very helpful to include files when you want to apply the same HTML or PHP code to
multiple pages of a website. There are two ways to include file in PHP.
1. include
2. require
PHP include
PHP include is used to include a file on the basis of given path. You may use a
relative or absolute path of the file.
Syntax
There are two syntaxes available for include:
Example
File: menu.html
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php
Home |
PHP |
Java |
HTML
This is Main Page
PHP require
PHP require is similar to include, which is also used to include files. The only
difference is that it stops the execution of script if the file is not found whereas include
doesn't.
Syntax
There are two syntaxes available for require:
require 'filename';
Or
require ('filename');
Example
File: menu.html
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: require1.php
Output:
Home |
PHP |
Java |
HTML
This is Main Page