WT - Unit 4
WT - Unit 4
Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Unit 4
PHP Programming: Introduction to PHP, Creating PHP script, Running PHP
script. Working with variables and constants: Using variables, Using constants, Data types,
Operators. Controlling program flow: Conditional statements, Control statements, Arrays,
functions.
Introduction to PHP
Hypertext Preprocessor (PHP) is a server-side scripting language designed specifically for
web development, but it is also used as a general-purpose programming language.
It is an open-source which means it is free to download and which is very simple to learn
and use. PHP contain text, HTML, CSS, JavaScript, and PHP code and is saved with “.php”
extension.
Unlike client-side languages like JavaScript, which are executed on the user’s browser, PHP
scripts run on the server. The results are then sent to the client’s web browser as plain
HTML.
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.), is compatible with
almost all servers used today (Apache, IIS, etc.) andsupports a wide range of databases.
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.2 is
the latest version of PHP, which was released on 22 November 2022.
Features of PHP
Page 1
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Using PHP
Install a web server
Install PHP
Install a database, such as MySQL
You can install a server on your personal computer such as XAMPP server from the link below:
https://www.apachefriends.org/index.html
A PHP version and MySQL come out of the box when you install XAMPP server. You can use other
development server instead of XAMPP such as WAMPSERVER that you can download from here
(http://www.wampserver.com/en/).
Comments in PHP: A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the code.
Example
// This is a single-line comment
Page 2
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
PHP echo: PHP echo statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the echo statement
are:
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses: echo(), and echo.
o echo does not return any value.
o We can pass multiple strings separated by a comma (,) in echo.
o echo is faster than the print statement.
Example
1)
<?php
echo "Hello by PHP echo";
?>
2)
<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>
PHP Print: PHP print statement can be used to print the string, multi-line strings, escaping
characters, variable, array, etc. Some important points that you must know about the echo statement
are:
o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.
Example
1)
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
?>
2)
<?php
$msg="Hello print() in PHP";
print "Message is: $msg";
?>
Page 3
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
While on a Windows operating system, start the Apache server from the XAMPP control panel.
Browse to the "htdocs" directory. Save the following script as "hello.php" in it.
<?php
echo” Hello KHIT”
?>
Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the
"Hello World" message in the browser window.
Using variables
PHP Variables are one of the most fundamental concepts in programming. It is used to store
data that can be accessed and manipulated within your code.
Variables in PHP are easy to use, dynamically typed (meaning that you do not need to
declare their type explicitly), and essential for creating dynamic, interactive web
applications.
To declare a variable in PHP, you simply assign a value to it using the $ symbol followed
by the variable name.
$x = 5;
$y = "John";
Page 4
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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)
Page 5
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
2) Global Scope or Global Variable
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the “global”
keyword before the variable to refer to the global variable.
Example
<?php
$num = 20;
// Function to demonstrate use of global variable
function global_var() {
// We have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function: $num \n";
}
global_var();
echo "Variable num outside function: $num \n";
?>
3) Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of
function execution. To do this, we use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the variable.
Example
<?php
// Function to demonstrate static variables
function static_var() {
// Static Variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// First function call
static_var();
// Second function call
static_var();
?>
4) Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in the script, including
within functions. Common superglobals include $_GET, $_POST, $_SESSION, $_COOKIE,
$_SERVER, and $_GLOBALS.
Example
<?php
// Using $_SERVER superglobal to
Page 6
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
// get server information
echo $_SERVER['SERVER_NAME'];
?>
Using constants
Constants in PHP are identifiers or names that remain constant throughout the program and
cannot be changed during the execution.
Once a constant is defined, it cannot be undefined or redefined and always written in upper
case.
PHP constants can be defined by 2 ways:
1) Using define() function
2) Using const keyword
Example
<?php
// This creates a case-sensitive constant
define("WELCOME", "KHIT");
echo WELCOME . "\n";
Example
<?php
const SITE_NAME = 'KHIT';
echo SITE_NAME;
?>
Page 7
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Difference between Constants and Variables
Feature Constants Variables
Data types
PHP is a loosely typed language, which means variables do not need to be declared with a specific
data type. PHP allows eight different types of data types. PHP supports the following data types:
1) Predefined Data Types
Integer:
Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point.
They can be decimal (base 10), octal (base 8), or hexadecimal (base 16). The
default base is decimal (base 10). The octal integers can be declared with leading
0 and the hexadecimal can be declared with leading 0x.
The range of integers must lie between -2^31 to 2^31.
Example
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
Page 8
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Float (Double): Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form.
Example
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
echo "\n\n";
//returns data type and value
var_dump($sum)
?>
String: Hold letters or any alphabets, even numbers are included. These are written within double
quotes during declaration. The strings can also be written within single quotes, but they will be
treated differently while printing variables.
Example
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name ';
echo "\n\n";
//returns data type, size and value
var_dump($name)
?>
Boolean: Boolean data types are used in conditional testing. Hold only two values, either TRUE(1)
or FALSE(0). Successful events will return true and unsuccessful events return false.
Example
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Page 9
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Objects: Objects are defined as instances of user-defined classes that can hold both values and
functions and information for data processing specific to the class. When the objects are created,
they inherit all the properties and behaviours from the class, having different values for all the
properties.
Example
<?php
class gfg {
public $message;
function __construct($message) {
$this->message = $message;
}
function msg() {
return "This is an example of " . $this->message . "!";
}
}
$newObj = new gfg("Object Data Type");
echo $newObj->msg();
?>
Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are
used to perform operations on variables or values.
Arithmetic Operators: The arithmetic operators are used to perform simple mathematical
operations like addition, subtraction, multiplication, etc.
Operator Name Syntax Operation
Page 10
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Example
<?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";
?>
Logical: You can use Logical operators in PHP to perform logical operations on multiple expressions
together. Logical operators always return Boolean values, either true or false. Logical operators are
commonly used with conditional statements and loops to return decisions according to the Boolean
conditions.
Operator Name Syntax Operation
Page 11
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Comparison Operators: These operators are used to compare two elements and outputs the result
in boolean form.
Operator Name Syntax Operation
Page 12
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Returns True if $x is
> Greater Than $x > $y
greater than $y
Returns True if $x is
Greater Than or
>= $x >= $y greater than or equal to
Equal To
$y
Conditional or Ternary Operators: These operators are used to compare two values and take
either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These
are also used as a shorthand notation for if…else statement that we will read in the article on
decision making.
Syntax
$var = (condition)? value1 : value2;
Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations.
Operator Name Syntax Operation
Simple Addition
+= Add then Assign $x += $y
same as $x = $x + $y
Page 13
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
(quotient)
Divide then
Assign Simple division same
%= $x %= $y
(remainder) as $x = $x % $y
Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations.
Increment/Decrement Operators: These are called the unary operators as they work on single
operands. These are used to increment or decrement values.
Operator Name Syntax Operation
Page 14
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
then return $x
if ($x > 0) {
echo "The number is positive";
}
?>
2) 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
}
Page 15
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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: 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";
}
Page 16
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
}
else{
echo "Nothing to show";
}
?>
4) 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:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example
<?php
$n = "February";
switch($n) {
case "January":
Page 17
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
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";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>
Control statements: PHP Loops are used to repeat a block of code multiple times based on a given
condition.
1) for: PHP for loop is used when you know exactly how many times you want to iterate through a
block of code. It consists of three expressions
Synatx
for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}
Page 18
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Example
<?php
2) while: The while loop is also an entry control loop like for loops. It first checks the condition at
the start of the loop and if its true then it enters into the loop and executes the block of statements,
and goes on executing it as long as the condition holds true.
Syntax
while ( condition ) {
// Code is executed
}
Example
<?php
$num = 1;
while ($num <= 5) {
echo $num . " ";
$num++;
}
?>
3) do while: The do-while loop is an exit control loop which means, it first enters the loop,
executes the statements, and then checks the condition. Therefore, a statement is executed at least
once using the do…while loop. After executing once, the program is executed as long as the
condition holds true.
Syntax
do {
// Code is executed
} while ( condition );
Example
<?php
$num = 1;
do {
echo $num . " ";
$num++;
} while ($num <= 5);
?>
4) foreach: This foreach loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax
foreach ( $array as $value ) {
Page 19
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
// Code to be executed
}
// or
Example
<?php
echo "\n";
Arrays
Arrays in PHP are a type of data structure that allows us to store multiple elements of similar or
different data types under a single variable thereby saving us the effort of creating a different
variable for every data. The arrays are helpful to create a list of elements of similar types, which
can be accessed using their index or key.
There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
Indexed array:
PHP index is represented by number which starts from 0. We can store number, string and object in
the PHP array. All PHP array elements are assigned to an index number by default.
Example
<?php
$season=array("summer","winter","spring","autumn");
Page 20
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Associative array:
We can associate name with each array elements in PHP using => symbol.
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Multidimensional array:
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Functions
A function is a block of code written in a program to perform some specific task. PHP provides us
with two major types of functions:
1) Built-in functions: PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so
on.
2) User Defined Functions: Apart from the built-in functions, PHP allows us to create our
own customised functions called the user-defined functions. Using this we can create our
own packages of code and use it wherever necessary by simply calling it.
Features
1) Reusability
2) Easier error detection
3) Easily maintained
Page 21
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Syntax
function function_name(){
executable code;
}
Example
<?php
function funckhit()
{
echo "This is KHIT";
}
Example
<?php
// pass by value
function valkhit($num) {
$num += 2;
return $num;
}
// pass by reference
function refkhit(&$num) {
$num += 10;
return $num;
}
$n = 10;
valkhit($n);
echo "The original value is still $n \n";
refkhit($n);
echo "The original value changes to $n";
?>
Page 22