0% found this document useful (0 votes)
27 views

UNIT 1-PHP-IIIBCA

Uploaded by

gansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

UNIT 1-PHP-IIIBCA

Uploaded by

gansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

SEMESTER VI UNIT I

PHP PROGRAMMING

UNIT- I : INTRODUCTION TO PHP


Essentials of PHP - Operators and Flow Control - Strings and Arrays.

Introduction to PHP

PHP is an open-source, interpreted, and object-oriented scripting language that can be


executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the
dynamic page.).

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:

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content
of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 1


 PHP is free to download and use
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code is executed on the server, and the result is returned to the browser as plain
HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
With PHP you are not limited to output HTML. You can output images or PDF files. You can
also output any text, such as XHTML and XML.

Why PHP?

 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource
 PHP is easy to learn and runs efficiently on the server side

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.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 2


Web Development

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.

HTML - HTML is used to design static webpage.

CSS - CSS helps to make the webpage content more effective and attractive.

JavaScript - JavaScript is used to design an interactive website.

PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.

Basic PHP Syntax

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.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 3


Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

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:

My first PHP page

Hello World!

EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
OUTPUT:
My first PHP script!

PHP Case Sensitivity

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

ECHO is the same as echo:


<html>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 4


<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
OUTPUT:
Hello World!
Hello World!
Hello World!

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.

The syntax of PHP echo is given below:

1. void echo ( string $arg1 [, string $... ] )


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.

Creating First PHP scripts

First PHP Script

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:

1. Step 1: Create a new PHP file

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.

2. Step 2: Opening and closing PHP tags

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:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 5


<?php
//your code here
?>

3.Step 3: Writing your first PHP script

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.

Step 4: Running your PHP script

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.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back
to their own work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code
 Leave out some parts of your code

Syntax for comments in PHP code:


// This is a single-line comment
# This is also a single-line comment
/* This is a
multi-line comment */

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 6


single Line Comments

Single line comments start with //.


Any text between // and the end of the line will be ignored (will not be executed).
Also use # for single line comments,

Example:

<body>
<?php
// Outputs a welcome message:
echo "Welcome Home!";
?>
</body>
</html>

Output:

Welcome Home

PHP Multiline Comment


Multi-line Comments

Multi-line comments start with /* and end with */.


Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

<!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).

Rules for PHP variables:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 7


 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)

Example:

<!DOCTYPE html>
<html>
<body>
<?php
$txt = "how are you";
echo "Hai $txt!";
?>
</body>
</html>

Output:

Hai how are you

Example:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>

Output:

PHP is a Loosely Typed Language

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 8


$x = 5; // $x is an integer
$y = "John"; // $y is a string

echo $x;
echo $y;
?>
</body>
</html>

Output:

5john

Get the Type

To get the data type of a variable, use the var_dump() function.

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)

Assign String to a 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>
Output:
John

Assign Multiple Values

You can assign the same value to multiple variables in one line:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 9


!DOCTYPE html>
<html>
<body>
<?php
$x = $y = $z = "Fruit";
echo $x;
echo $y;
echo $z;
?>
</body>
</html>
Output:
FruitFruitFruit
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

/ Division $x / $y Quotient of $x and $y

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 10


% Modulus $x % $y Remainder of $x divided
by $y

** Exponentiation $x ** $y Result of raising $x to the


$y'th power

<?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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 11


Modulus: 1

PHP Assignment Operators

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.

Assignment Same as... Description

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";

// Add then assign operator


$y = 100;

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 12


$y += 200;
echo $y, "\n";

// Subtract then assign operator


$y = 70;
$y -= 10;
echo $y, "\n";

// Multiply then assign operator


$y = 30;
$y *= 20;
echo $y, "\n";

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";

// Divide then assign(remainder) operator


$y = 50;
$y %= 5;
echo $y;
?>
output
75
300
60
600
20
0

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 13


are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they
are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to


equal to $y

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

<=> Spaceship $x <=> $y Returns an integer less than, equal to, or


greater than zero, depending on if $x is less
than, equal to, or greater than $y.
Introduced in PHP 7.

<?php
$a = 80;
$b = 50;
$c = "80";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 14


// Here var_dump function has been used to
// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
output
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 15


$x-- Post-decrement Returns $x, then decrements $x by one

<?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

3 First increments then prints


3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 16


or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 17


output
GeeksforGeeks!!!
GeeksforGeeks!!!

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of the
same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

<?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";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 18


var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
output
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result

?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.


The value of $x
is expr2 if expr1 =
TRUE.
The value of $x
is expr3 if expr1 =
FALSE

?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.


The value of $x
is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or
is NULL, the value of $x
is expr2.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 19


Introduced in PHP 7

Storing data in Variable

Use the variable name on the left side of an assignment statement.

Example sets the value of the variable alpha . The value generated on the right side of the
assignment statement is stored in the variable.

To store a value in a variable

 Use the variable name on the left side of an assignment statement.

The following example sets the value of the variable alpha.

alpha = (beta * 6.27) / (gamma + 2.1)

The value generated on the right side of the assignment statement is stored in the
variable.

Assign String to a 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>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 20


OUTPUT

John

Assign Multiple Values

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 is a sequence of characters, like "Hello world!".

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>";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 21


var_dump($y);
?>
</body>
</html>

Output:

string(12) "Hello world!"


string(12) "Hello world!"

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: decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2) notation

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);

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 22


?>
</body>
</html>
Output:
float(10.365)

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

<!DOCTYPE html>
<html>
<body>
<?php
$x = true;
var_dump($x);
?>
</body>
</html>
Output:
bool(true)

PHP Array

An array stores multiple values in one single variable.

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:

[0]=> string(5) "Volvo"


[1]=> string(3) "BMW"
[2]=> string(6) "Toyota"

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 23


When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.

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 . "!";
}
}

$myCar = new Car("red", "Volvo");


var_dump($myCar);
?>

</body>
</html>
Output:
object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }

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.

Variables can also be emptied by setting the value to NULL:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 24


<html>
<body>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
Output:
NULL

Change Data Type

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);
?>

<p>Line breaks were added for better readability.</p>


</body>
</html>
Output:

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.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 25


PHP String

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:

Hello text within single quote

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 26


1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>

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 |FLOW CONTROL


Decision Making

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:

1. if Statement: This statement allows us to set a condition. On being TRUE, the


following block of code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
Flowchart:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 27


Example
<?php
$x = 12;

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";
}

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 28


?>
Output

The number is negative


Flowchart:

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";
}

elseif ($x == "August") {


echo "Happy Independence Day!!!";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 29


}

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:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 30


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":
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";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 31


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";
}
?>
Output
Its February
Flowchart:

Looping Statements

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 32


Looping statements, also known as iteration or repetition statements, are used in
programming to repeatedly execute a block of code. They are essential for performing tasks
such as iterating over elements in a list, reading data from a file, or executing a set of
instructions a specific number of times. Here are some common types of looping
statements:
PHP for Loop
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:
 Initialization: Sets the initial value of the loop variable.
 Condition: Checks if the loop should continue.
 Increment/Decrement: Changes the loop variable after each iteration.
Sytntax

for ( Initialization; Condition; Increment/Decrement ) {


// Code to be executed
}
Example: Printing numbers from 1 to 5 using for loop.

<?php

// Code to illustrate for loop


for ($num = 1; $num <= 5; $num += 1) {
echo $num . " ";
}

?>
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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 33


while ($num < 20) {
echo $num . "\n";
$num += 2;
}
?>
OUTPUT:
10
12
14
16
18

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 34


16
18
foreach loop
The foreach loop in PHP is a powerful and convenient way to iterate over arrays and
objects.
The foreach loop though iterates over an array of elements, the execution is simplified and
finishes the loop in less time comparatively..
The foreach loop in PHP is specifically designed for iterating over arrays and objects.
Unlike traditional loops (like for or while), foreach automatically manages the iteration,
which simplifies the code and reduces the potential for errors.
The key advantages of using foreach include :
 Easy to read and write.
 Automatically handles both keys and values in associative arrays.
 Unlike for loops, you don’t need to manually manage index counters.
Syntax:
foreach( $array as $element ) {
// PHP Code to be executed
}
Example:
<?php

$arr = [10, 20, 30, 40, 50];

foreach ($arr as $element) {


echo $element . PHP_EOL;
}

?>
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) {

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 35


break;
}
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

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 36


The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
PHP 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.
Types of Array in PHP
Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value
can be assigned a specific key.
Multidimensional Arrays: An array that contains a single or multiple arrays within it and
can be accessed via multiple indices
1.Indexed or Numeric Arrays

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]=>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 37


string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
.Access Indexed Arrays

To access an array item you can refer to the index number.

<!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.";
?>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 38


</body>
</html>

Output

Peter is 35 years old.

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

Update Array Item

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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 39


$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
?>
output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}
Add Array Item

To add items to an existing array, you can use the bracket [] syntax.

<?php
$fruits = array("Apple", "Banana", "Cherry");
$fruits[] = "Orange";

//Output the array:


var_dump($fruits);
?>
output
array(4) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
[2]=>
string(6) "Cherry"
[3]=>
string(6) "Orange"
}

Remove Array Item

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);

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 40


var_dump($cars);
?>
output
array(4) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
[2]=>
string(6) "Cherry"
[3]=>
string(6) "Orange"
}
3) Multidimensional Arrays

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

Volvo: Ordered: 100. Sold: 96


BMW: Ordered: 60. Sold: 59
Toyota: Ordered: 110. Sold: 100

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 41


Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 42

You might also like