UNIT 1-PHP-IIIBCA
UNIT 1-PHP-IIIBCA
PHP PROGRAMMING
Introduction to PHP
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November. Some important
points need to be noticed about PHP are as followed:
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
Why PHP?
PHP Features
performance:
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
PHP is widely used in web development nowadays. PHP can develop dynamic websites
easily. But you must have the basic the knowledge of following technologies for web
development as well.
o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript.
So, learn these technologies for better implementation of PHP.
CSS - CSS helps to make the webpage content more effective and attractive.
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
<?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.
Example
A simple .php file with both HTML code and PHP code
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
OUTPUT:
Hello World!
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
OUTPUT:
My first PHP script!
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Example
PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.
To get started, you'll need a text editor to write your PHP code. You can use any text editor
you prefer, such as Notepad++, Sublime Text, or Visual Studio Code. Once you have your
text editor set up, follow the steps below to create your first PHP script:
Start by creating a new file with a .php extension, such as "first_script.php". This
extension is necessary to indicate that the file contains PHP code.
In PHP, you need to enclose your code within opening and closing PHP tags. These
tags allow the PHP interpreter to identify and execute the PHP code within them.
Open your PHP file and add the following tags:
Now you can start writing your PHP script within the PHP tags. Here's an example of
a simple PHP script that prints "Hello, World!" to the browser:
<?php
echo "Hello by PHP echo";
?>
In this script, the echo statement is used to output the string "Hello, World!" to the
browser. The semicolon (;) at the end of the line indicates the end of the statement.
To run your PHP script, you'll need a web server with PHP installed. You can either install a
local server like XAMPP or WAMP on your computer or use an online development
environment like Replit or PHPFiddle.
If you're using a local server, make sure to place your PHP file in the appropriate directory,
typically the "htdocs" folder for XAMPP or the "www" folder for WAMP. Then, access your
script through the browser by entering the server's URL followed by the name of your PHP
file (e.g., http://localhost/first_script.php).
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.
Example:
<body>
<?php
// Outputs a welcome message:
echo "Welcome Home!";
?>
</body>
</html>
Output:
Welcome Home
<!DOCTYPE html>
<html>
<body>
<?php
/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";
?>
</body>
</html>
Output:
Welcome Home!
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "how are you";
echo "Hai $txt!";
?>
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>
Output:
PHP automatically associates a data type to the variable, depending on its value
Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the
variable
!DOCTYPE html>
<html>
<body>
<?php
echo $x;
echo $y;
?>
</body>
</html>
Output:
5john
Example
The var_dump() function returns the data type and the value:
!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
var_dump($x);
?>
</body>
</html>
Output:
int(5)
Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
<!DOCTYPE html>
<html>
<body>
<?php
$x = "John";
echo $x;
?>
</body>
</html>
Output:
John
You can assign the same value to multiple variables in one line:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
<?php
// Define two numbers
$x = 10;
$y = 3;
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
x=y x=y The left operand gets set to the value of the
expression on the 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
<?php
// Simple assign operator
$y = 75;
echo $y, "\n";
The PHP comparison operators are used to compare two values (number or string):
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they
are not of the same type
<?php
$a = 80;
$b = 50;
$c = "80";
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
output
PHP has two operators that are specially designed for strings.
<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");
var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
The PHP conditional assignment operators are used to set a value depending on conditions:
Example sets the value of the variable alpha . The value generated on the right side of the
assignment statement is stored in the variable.
The value generated on the right side of the assignment statement is stored in the
variable.
Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
<!DOCTYPE html>
<html>
<body>
<?php
$x = "John";
echo $x;
?>
</body>
</html>
John
You can assign the same value to multiple variables in one line:
<!DOCTYPE html>
<html>
<body>
<?php
$x = $y = $z = "Fruit";
echo $x;
echo $y;
echo $z;
?>
</body>
</html>
OUTPUT
FruitFruitFruit
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 can be any text inside quotes. You can use single or double quotes:
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
Output:
PHP Integer
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
Output:
int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
PHP Boolean
<!DOCTYPE html>
<html>
<body>
<?php
$x = true;
var_dump($x);
?>
</body>
</html>
Output:
bool(true)
PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Output:
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
Let's assume we have a class named Car that can have properties like model, color, etc. We
can define variables like $model, $color, and so on, to hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
If you create a __construct() function, PHP will automatically call this function when you
create an object from a class.
<!DOCTYPE html>
<html>
<body>
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
</body>
</html>
Output:
object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }
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.
If you assign an integer value to a variable, the type will automatically be an integer.
If you assign a string to the same variable, the type will change to a string:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
var_dump($x);
echo "<br>";
$x = "Hello";
var_dump($x);
?>
int(5)
string(5) "Hello"
Line breaks were added for better readability.
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP.
We will not talk about the resource type here, since it is an advanced topic.
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports
only 256-character set and so that it does not offer native Unicode support. There are 4 ways
to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to
specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal
backslash (\) use double backslash (\\). All the other instances with backslash such as \r or \n,
will be output same as they specified instead of having any special meaning.
For Example
Following some examples are given to understand the single quoted PHP String in a better
way:
Example 1
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.
Example 1
Output:
Hello text within single quote
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is
provided after this heredoc <<< operator, and immediately a new line is started to write any
text. To close the quotation, the string follows itself and then again that same identifier is
provided. That closing identifier must begin from the new line without any whitespace or tab.
PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action
would be performed as asked by the user. It’s just like a two- way path. If you want
something then go this way or else turn that way. To use this feature, PHP provides us with
Four conditional statements :
if statement
if…else statement
if…elseif…else statement
switch statement
Let us now look at each one of these in details:
if ($x > 0) {
echo "The number is positive";
}
?>
Output
The number is positive
2) if…else Statement
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the block
of code within if will be executed. But what if the condition is not TRUE and we want to
perform an action? This is where else comes into play. If a condition is TRUE then if block
gets executed, otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example
<?php
$x = -12;
if ($x > 0) {
echo "The number is positive";
}
else{
echo "The number is negative";
}
3) if…elseif…else Statement
if…elseif…else Statement: This allows us to use multiple if…else statements. We use this
when there are multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
else{
echo "Nothing to show";
}
?>
Output
Happy Independence Day!!!
Flowchart:
4) switch Statement
Switch Statement: The “switch” performs in various cases i.e., it has various cases to
which it matches the condition and appropriately executes a particular case block. It first
evaluates an expression and then compares with the values of each case. If a case matches
then the same case is executed. To use switch, we need to get familiar with two different
keywords namely, break and default.
1. The break statement is used to stop the automatic control flow into the next cases and
exit from the switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(n) {
case statement1:
switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
Looping Statements
<?php
?>
Output
12345
2. The while loop is the simple loop that executes nested statements repeatedly while the
expression value is true. The expression is checked every time at the beginning of the loop,
and if the expression evaluates to true then the loop is executed otherwise loop is
terminated.
Syntax:
while (if the condition is true) {
// Code is executed
}
EXAMPLE
<?php
// Declare a number
$num = 10;
// While Loop
3. The do-while loop is very similar to the while loop, the only difference is
that the do-while loop checks the expression (condition) at the end of
each iteration. In a do-while loop, the loop is executed at least once when
the given expression is “false”. The first iteration of the loop is executed
without checking the condition.
SYNTAX
do {
// Statements to be executed
} while (condition);
The block of statements within the do block is executed unconditionally for the first
time.
After executing the block, the condition specified after the while keyword is evaluated.
If the condition evaluates to true, the loop body is executed again. If the condition
evaluates to false, the loop terminates, and program execution moves to the next
statement after the loop.
Example
<?php
// Declare a number
$num = 10;
// do-while Loop
do
{
echo $num . "\n";
$num += 2;
} while ($num < 20);
?>
output
10
12
14
?>
output:
10
20
30
40
50
break statement
The break statement can be used to jump out of different kind of loops.
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
PHP Continue
The continue statement can be used to jump out of the current iteration of a loop, and
continue with the next.
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
These type of arrays can be used to store any type of element, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two different
ways.
Syntax:
array(value1, value2, value3, etc.)
Example:
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
</pre>
</body>
</html>
output
array(3) {
[0]=>
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
?>
</body>
</html>
output
Volvo
BMW
Toyota
2) Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every
value can be assigned with a user-defined key of string type.
Syntax:
array(key=>value,key=>value,key=>value,etc.)
Parameter Description
key Specifies the key (numeric or string)
value Specifies the value
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output
Create Array
create arrays by using the array() function:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
output
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Access Array Item
To access an array item, you can refer to the index number for indexed arrays, and the key
name for associative arrays.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
?>
output
Toyota
To update an existing array item, you can refer to the index number for indexed arrays, and
the key name for associative arrays.
Example:
<?php
To add items to an existing array, you can use the bracket [] syntax.
<?php
$fruits = array("Apple", "Banana", "Cherry");
$fruits[] = "Orange";
To remove an existing item from an array, you can use the array_splice() function.
With the array_splice() function you specify the index (where to start) and how many items
you want to delete.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
Multi-dimensional arrays are such arrays that store another array at each index instead of a
single element. In other words, we can define multi-dimensional arrays as an array of arrays.
As the name suggests, every element in this array can be an array and they can also hold
other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed
using multiple dimensions.
Example:
Create a multidimensional array:
<!DOCTYPE html>
<html>
<body>
<?php
// A two-dimensional array
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
echo $cars[0][0].": Ordered: ".$cars[0][1].". Sold: ".$cars[0][2]."<br>";
echo $cars[1][0].": Ordered: ".$cars[1][1].". Sold: ".$cars[1][2]."<br>";
echo $cars[2][0].": Ordered: ".$cars[2][1].". Sold: ".$cars[2][2]."<br>";
?>
</body>
</html>
Output