0% found this document useful (0 votes)
8 views40 pages

UNIT1 PHP

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It offers features like dynamic content management, session tracking, and compatibility with various databases, making it a popular choice for developers. The document also outlines PHP's history, installation requirements, variable declaration, and data types.

Uploaded by

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

UNIT1 PHP

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It offers features like dynamic content management, session tracking, and compatibility with various databases, making it a popular choice for developers. The document also outlines PHP's history, installation requirements, variable declaration, and data types.

Uploaded by

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

0

UNIT-1 GORISH MITTAL

What is 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 8.2 is the
latest version of PHP, which was released on 24 November 2022. 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.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web applications
with MySQL database.

o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


1

o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration form.

PHP Features
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below:

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.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:

PHP code can be easily embedded within HTML tags and script. PHP was designed to work with
HTML, and as such, it can be embedded into the HTML code.

You can create PHP files without any html tags and that is called Pure PHP file .

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


2

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.

Web servers Support:

PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.

Security:

PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP can do the same work
in a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.

Scripting Language

A script or scripting language is a computer language that does not need the compilation step
and is rather interpreted one by one at runtime. It is where the script is written and where
instructions for a run-time environment are written. In contrast to programming languages that
are compiled first before running, scripting languages do not compile the file and execute the file
without being compiled.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


3

Server-side language
Code running in the browser is known as client-side code and is primarily concerned with improving the
appearance and behavior of a rendered web page. This includes selecting and styling UI components,
creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly
involves choosing which content is returned to the browser in response to requests. The server-side
code handles tasks like validating submitted data and requests, using databases to store and retrieve
data and sending the correct data to the client as required.

Interpreted language
run through a program line by line and execute each command.

Session Tracking
tracks a user's requests and maintains their state. It is a mechanism used to store information on
specific users and in order to recognize these user's requests when they connect to the web
server.

Basic PHP Syntax


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.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


4

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:

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

PHP Versions
PHP Version 1.0

• As mentioned before, PHP development started way back in 1994 and was developed
by Rasmus Lerdorf. He used C as a scripting language He originally used them to
maintain his personal homepage. He later extended these code specs to work with web
forms and databases.

PHP Version 2.0

• The initial version of PHP, though not very refined gained a lot of popularity by the
developer community when it was released for public usage in 1995.
• As its popularity continued to grow, a formal developer team was formed to work on
the inconsistencies of version 1.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


5

PHP Version 3.0

• As PHP’s popularity grew, it attracted the attention of Zeev Suraski and Andi Gutmans.
• In 1997, Zeev Suraski and Andi Gutmans rewrote the internal PHP parser and formed
the basic structure for PHP 3. The official launch of PHP 3 was done in June 1998 once
the public testing was completed.

PHP Version 4.0

• Finally, in the year 2000, PHP version 4 powered by Zend Engine 1 was released for
public usage.
• By 2008, PHP version 4 had evolved and reached 4.4.9. However, it is no more
supported for security updates.

5. PHP Version 5.0 and 6.0

• In 2004, this was released and was powered by Zend Engine 2.


• It included several new features and better support for Object-Oriented
Programming (OOP), PDO (PHP Data Objects) extension which provides a lightweight
interface to programmers for accessing database and many other performance
improvements.
• It scaled up to version 5.6. In December 2018, official support for PHP security ended
but Debian continued to provide security support until 2020.

Version 7.0

• During the period of 2016 and 2017, PHP underwent major changes and the update was
released as PHP 7. The version number selected for rolling out this release has to face several
debates.
• In spite of the PHP Unicode project not officially released, several books had referencing
included in them addressing it as PHP version 6. If an actual release would have been also
rolled out as version 6, it would have caused confusion in the developer community. Hence, it
was decided to release this update as version 7.0.
• PHP 7 is based on phpng which stands for PHP next Generation. PHP Next Generation was an
initiative by developers to overcome the high-performance constraints of previous PHP
versions. The phpng branch served as the base branch for PHP version 7.0.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


6

PHP Version Release Date Support EOL

1.0 8 June 1995

2.0 1 November 1997

3.0 6 June 1998 20 October 2000

4.0 22 May 2000 23 June 2001

5.0 13 July 2004 5 September 2005

5.1 24 November 2005 24 August 2006

5.2 2 November 2006 6 January 2011

5.3 30 June 2009 14 August 2014

5.4 1 March 2012 3 September 2015

5.5 20 June 2013 10 July 2016

5.6 28 August 2014 31 December 2018

7.0 3 December 2015 3 December 2018

7.1 1 December 2016 1 December 2019

7.2 30 November 2017 30 November 2020

7.3 28 November 2019 6 December 2021

7.4 28 August 2019 28 November 2022

8.0 26 November 2020 26 November 26 2023

8.1 25 November 2021 25 November 2024

8.2 24 November 2022 24 November 2025

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


7

---------------------------------------------------------------------

Installation of PHP
In order to develop and run PHP Web pages three vital components need to be installed on
your computer system.
• Web Server − PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
available Apache Server. Download Apache for free here
− https://httpd.apache.org/download.cgi
• Database − PHP will work with virtually all database software, including Oracle
and Sybase but most commonly used is freely available MySQL database.
Download MySQL for free here − https://www.mysql.com/downloads/
• PHP Parser − In order to process PHP script instructions a parser must be installed
to generate HTML output that can be sent to the Web Browser.

PHP Parser Installation


Before you proceed it is important to make sure that you have proper environment setup on your
machine to develop your web programs using PHP.
Type the following address into your browser's address box.
http://127.0.0.1/info.php
If this displays a page showing your PHP installation related information then it means you have
PHP and Webserver installed properly.

Early years when the servers are costly we have to setup a local environment for php by
installing and configuring apache serve and sql data base in our system but now by the
introduction of XAMMP and WAMMP server we did not do it separately or manually. To run
PHP for the web, we need to install a web server like Apache and a database like MySQL – and
both are supported by XAMPP.

XAMPP is a local server that can run smoothly on our personal computer, and is accepted in
both Windows and Linux. It also helps you test websites and see if they work before actually
publishing them to a web server.

----------------------------------- Not Completed-------------==========================


PHP NOTES FOR MGSU EXAMS GORISH MITTAL
8

BUILDING BLOCKS OF PHP

PHP Variables
Variables in a program are used to store some values or data that can be used later in a program.
The variables are also like containers that store character values, numeric values, memory
addresses, and strings

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important
points to know about variables:

o As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

$variablename=value;

Rules for declaring PHP variable:

o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


9

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

Output:
string is: hello string
integer is: 200
float is: 44.6
-----------------------------------------------

PHP Data Type


Data Types define the type of data a variable can store. PHP allows eight different types of data
types. All of them are discussed below. There are pre-defined, user-defined, and special data
types.

The predefined data types are:

1. Boolean
2. Integer

3. Double
4. String

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


10

The user-defined (compound) data types are:

1. Array
2. Objects

The special data types are:


1. NULL

2. Resource

The first five are called simple data types and the last three are compound data types:

1. Integer: Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point. range of integers must lie between -

2^31 to 2^31.

2. Double: Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form. By default, the variables add a

minimum number of decimal places. The Double data type is the same as a float as
floating-point numbers or real numbers.

$val1 = 50.85;
$val2 = 654.26;

3. 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.

$name = "Krishna";
echo "The name of the Geek is $name \n";

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


11

4. 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.
NULL type values are also treated as false in Boolean. Apart from NULL, 0 is also considered

false in boolean. If a string is empty then it is also considered false in boolean data type.

<?php
if(TRUE)

echo "This condition is TRUE";


if(FALSE)

echo "This condition is not TRUE";


?>

5. Array: Array is a compound data type that can store multiple values of the same data type.
Below is an example of an array of integers. It combines a series of data that are related

together.

<?php

$intArray = array( 10, 20 , 30);

echo "First Element: $intArray[0]\n";


echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n\n";

//returns data type and value


var_dump($intArray);

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


12

6. 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.

7. NULL: These are special types of variables that can hold only one value i.e., NULL. We
follow the convention of writing it in capital form, but it’s case-sensitive. If a variable is
created without a value or no value, it is automatically assigned a value of NULL. It is
written in capital letters.

<?php

$nm = NULL;

echo $nm; // this will return no


output

// return data type

var_dump($nm);

?>

PHP Expression
Almost everything in a PHP script is an expression. Anything that has a value is an expression. In
a typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=)

Syntax

$x=100; //100 is an expression

$a=$b+$c; //b+$c is an expression

$c=add($a,$b); //add($a,$b) is an expresson

$val=sqrt(100); //sqrt(100) is an expression

$var=$x!=$y; //$x!=$y is an expression

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


13

PHP Operators
Operators are used to performing operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them, and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and
2, performs an addition operation on them to give 3.

Just like any other programming language, PHP also supports various types of operations like
arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables, or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups of
operators:

Arithmetic Operators
Logical or Relational Operators
Comparison Operators
Conditional or Ternary Operators
Assignment Operators
Spaceship Operators (Introduced in PHP 7)
Array Operators
Increment/Decrement Operators
String Operators

Arithmetic Operators:

The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax
and operations in PHP.
Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


14

Operator Name Syntax Operation

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands

Logical or Relational Operators:

These are basically used to operate with conditional statements and expressions. Conditional
statements are based on conditions. Also, a condition can either be met or cannot be met so
the result of a conditional statement can either be true or false. Here are the logical operators
along with their syntax and operations in PHP.
Operator Name Syntax Operation

Logical $x and
and AND $y True if both the operands are true else false

or Logical OR $x or $y True if either of the operands is true else false

Logical True if either of the operands is true and false if


xor XOR $x xor $y both are true

Logical
&& AND $x && $y True if both the operands are true else false

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


15

Operator Name Syntax Operation

|| Logical OR $x || $y True if either of the operands is true else false

Logical
! NOT !$x True if $x is false

Comparison Operators: These operators are used to compare two elements and outputs the
result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.

Operator Name Syntax Operation

Returns True if both the operands are


== Equal To $x == $y equal

Returns True if both the operands are not


!= Not Equal To $x != $y equal

Returns True if both the operands are


<> Not Equal To $x <> $y unequal

$x === Returns True if both the operands are


=== Identical $y equal and are of the same type

Returns True if both the operands are


!== Not Identical $x == $y unequal and are of different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

Less Than or Returns True if $x is less than or equal to


<= Equal To $x <= $y $y

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


16

Operator Name Syntax Operation

Greater Than or Returns True if $x is greater than or equal


>= Equal To $x >= $y 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;

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if the
condition is true then the left result of the colon is accepted
?: Ternary otherwise the result is on right.

Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations. Here are the assignment operators along with their syntax and
operations, that PHP provides for the operations.
Operator Name Syntax Operation

Operand on the left obtains the value of


= Assign $x = $y the operand on the right

+= Add then Assign $x += $y Simple Addition same as $x = $x + $y

-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


17

Operator Name Syntax Operation

*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y

Divide then Assign


/= (quotient) $x /= $y Simple division same as $x = $x / $y

$x %=
Divide then Assign
%= $y Simple division same as $x = $x % $y
(remainder)

Array Operators: These operators are used in the case of arrays. Here are the array operators
along with their syntax and operations, that PHP provides for the array operation.
Operator Name Syntax Operation

+ Union $x + $y Union of both i.e., $x and $y

== Equality $x == $y Returns true if both has same key-value pair

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value pair in


=== Identity $y the same order and of the same type

Non- $x !==
!== Identity $y Returns True if both are not identical to each other

<> Inequality $x <> $y Returns True if both are unequal

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


18

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

++ Pre-Increment ++$x First increments $x by one, then return $x

— Pre-Decrement –$x First decrements $x by one, then return $x

++ Post-Increment $x++ First returns $x, then increment it by one

— Post-Decrement $x– First returns $x, then decrement it by one

String Operators: This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then assigns, same


.= assignment $x.=$y as $x = $x.$y

<?php

$x = "Geeks";

$y = "for"; Output

$z = "Geeks!!!"; GeeksforGeeks!!!

echo $x . $y . $z, "\n"; GeeksforGeeks!!!

$x .= $y . $z;

echo $x;

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


19

Spaceship Operators:

PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator
or combined comparison operator is denoted by “<=>“. These operators are used to compare
values but instead of returning the boolean results, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is
greater, it returns 1. The following table shows how it works in detail:

$x <=>
$x < $y $y Identical to -1 (right is greater)

$x <=>
$x > $y $y Identical to 1 (left is greater)

$x <= $x <=> Identical to -1 (right is greater) or identical to 0 (if both are


$y $y equal)

$x >= $x <=> Identical to 1 (if left is greater) or identical to 0 (if both are
$y $y equal)

$x == $x <=>
$y $y Identical to 0 (both are equal)

$x <=>
$x != $y $y Not Identical to 0

<?php
Output
$x = 50;
0
$y = 50;
1
$z = 25;
-1
echo $x <=> $y;
1
echo "\n";

echo $x <=> $z;


1

echo "\n"; -1
echo $z <=> $y;

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


20

echo "\n";

// We can do the same for Strings

$x = "Ram";

$y = "Krishna";

echo $x <=> $y;

echo "\n";

echo $x <=> $y;

echo "\n";

echo $y <=> $x;

?>

PHP Constants
Constants are either identifiers or simple names that can be assigned any fixed values. They are
similar to a variable except that they can never be changed. They remain constant throughout the
program and cannot be altered during execution. Once a constant is defined, it cannot be
undefined or redefined. Constant identifiers should be written in upper case following the
convention. By default, a constant is always case-sensitive, unless mentioned. A constant name
must never start with a number. It always starts with a letter or underscores, followed by letter,
numbers or underscore. It should not contain any special characters except underscore, as
mentioned.

PHP constants can be defined by 2 ways:

1. Using define() function


2. Using const keyword

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax
of define() function in PHP.

define(name, value, case-insensitive)

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


21

1. name: It specifies the constant name.


2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It
means it is case sensitive by default.

Let's see the example to define PHP constant using define().


1. <?php Output:
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?> Hello JavaTpoint PHP

Create a constant with case-insensitive name:

1. <?php Output:
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
Hello JavaTpoint PHP
3. echo MESSAGE, "</br>";
4. echo message; Hello JavaTpoint PHP
5. ?>

PHP constant: const keyword

PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const keyword
are case-sensitive.

1. <?php Output:
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE; Hello const by JavaTpoint PHP
4. ?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


22

Constant() function

There is another way to print the value of constants using constant() function instead of using the
echo statement.

The syntax for the following constant function:

constant (name)

1. <?php
2. define("MSG", "JavaTpoint"); Output:
3. echo MSG, "</br>"; JavaTpoint
4. echo constant("MSG"); JavaTpoint
5. //both are similar
6. ?>

PHP Switching Statement


The switch statement is similar to the series of if-else statements. The switch statement 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 it with the
values of each case. If a case matches then the same case is executed.

To use the switch, we need to get familiar with two different keywords namely, break and default.

❖ break: The break statement is used to stop the automatic control flow into the next cases
and exit from the switch case.

❖ default: The default statement contains the code that would execute if none of the cases
match.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


23

PHP Switch Flowchart

PHP Switch Example


1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
24

6. break;
7. case 20:
8. echo("number is equal to 20"); Output:
9. break;
10. default: number is equal to 20
11. echo("number is not equal to 10, 20 or 30");
12. }
13. ?>

PHP Flow Statements

PHP supports a number of traditional programming constructs for controlling the


flow of execution of a program.

The flow of the program always flow from top to bottom to change the flow of
program on certain condition we use various flow statement

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 code.

Conditional Statements

• if statements
• if ... else ... statements
• switch Statements --- defined above
Looping Statements

• while loops
• do ... while loops

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


25

Conditional Statement
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

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

1. if(condition){
2. //code to be executed
3. }

Flowchart

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


26

Example

1. <?php
2. $num=12; Output:
3. if($num<100){ 12 is less than 100
4. echo "$num is less than 100";
5. }
6. ?>

PHP If-else Statement


PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.

Syntax

1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

Flowchart

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


27

Example

1. <?php
2. $num=12;
Output:
3. if($num%2==0){
4. echo "$num is even number"; 12 is even number
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

PHP If-else-if Statement


The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.

Syntax

1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


28

Example

1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail"; }
5. else if ($marks>=34 && $marks<50) {
6. echo "D grade";
7. }
8. else if ($marks>=50 && $marks<65) {
9. echo "C grade";
10. }
Output:
11. else if ($marks>=65 && $marks<80) {
12. echo "B grade"; B Grade
13. }
14. else {
15. echo "Invalid input";
16. }
17. ?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


29

PHP nested if Statement


The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.

Syntax

1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }

Flowchart

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


30

Example

1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian") Output:
6. { Eligible to give vote
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>

PHP Loops or Looping Statement

Like any other language, loop in PHP is used to execute a statement or a block of statements,
multiple times until and unless a specific condition is met. This helps the user to save both time
and effort of writing the same code multiple times.

PHP supports four types of looping techniques;

for loop

while loop

do-while loop

foreach loop

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


31

For loop: This type of loops is used when the user knows in advance, how many times the block
needs to execute. That is, the number of iterations is known beforehand. These type of loops
are also known as entry-controlled loops. There are three main parameters to the code, namely
the initialization, the test condition and the counter.

Syntax:

for (initialization expression; test condition; update expression) {

// code to be executed

In for loop, a loop variable is used to control the loop. First initialize this loop variable to some
value, then check whether this variable is less than or greater than counter value. If statement is
true, then loop body is executed and loop variable gets updated . Steps are repeated till exit
condition comes.

Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: $num = 1;

Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: $num <= 10;

Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: $num += 2;

Example:

Output:
<?php 1
// code to illustrate for loop 3
for ($num = 1; $num <= 10; $num += 2) { 5

echo "$num \n"; 7


9
}

?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
32

Flow Diagram:

while loop: The while loop is also an entry control loop like for loops i.e., it first checks the
condition at the start of the loop and if its true then it enters the loop and executes the block of
statements, and goes on executing it as long as the condition holds true.
Syntax:

while (if the condition is true) {


// code is executed}

Example:
Output:
<?php 4
// PHP code to illustrate while loops 6
$num = 2; 8
while ($num < 12) { 10

$num += 2; 12

echo $num, "\n"; } ?>


PHP NOTES FOR MGSU EXAMS GORISH MITTAL
33

do-while loop: This is an exit control loop which means that it first enters the loop, executes
the statements, and then checks the condition. Therefore, a statement is executed at least once
on 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 (if condition is true);

Example:
<?php

// PHP code to illustrate do...while loops


Output:
$num = 2; 4
do { 6
$num += 2; 8
echo $num, "\n"; 10

} while ($num < 12); 12

?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
34

foreach loop: This 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_element as value) {

//code to be executed

Example:

<?php Output:
10
$arr = array (10, 20, 30, 40, 50, 60);
20
foreach ($arr as $val) {
30
echo "$val \n"; 40
} 50
$arr = array ("Ram", "Laxman", "Sita"); 60
Ram
foreach ($arr as $val) {
Laxman
echo "$val \n";
Sita
}?>

Note : one more type of loop is nested loop in which we call loop inside the loop. This is most
commonly used in the case of two dimensional array .

--------------------------------------------------------------------------

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


35

PHP Code Blocks

PHP is designed to work with HTML, so you can easily write and embed PHP code with
HTML. A PHP code block begins with <?php tag and ends with ?> tag.

<?php
//your php code goes here
?>

A code block is a list of statements grouped as one unit. In PHP we use {} to wrap code
blocks and notify the compiler by saying, "hey this is a group of statements." Although
statements cannot be combined like expressions, you can always put a sequence of statements
anywhere a statement can go by enclosing them in a set of curly braces.

Here both statements are equivalent –

if (3 == 2 + 1)

print("Good - I haven't totally lost my mind.");

if (3 == 2 + 1) { print("Good - I haven't totally");

print("lost my mind.");

PHP Browser Output

PHP provides the following methods for printing data in the browser:

1. print()
2. echo()

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


36

PHP Print

Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Print statement can be used with or without parentheses: print and print(). Unlike
echo, it always returns 1.

The syntax of PHP print is given below:

int print(string $arg)

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.

o <?php
o print "Hello by PHP print ";
o print ("Hello by PHP print()");
o ?>

PHP Echo

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:

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


PHP NOTES FOR MGSU EXAMS GORISH MITTAL
37

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.

o <?php
o echo "Hello by PHP echo";
o ?>

PHP echo: printing variable value

1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


38

Commenting PHP Code


A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP –

Single-line comments − They are generally used for short explanations or notes relevant to the
local code. Here are the examples of single line comments.

<?

# This is a comment, and

# This is the second line of the comment

// This is a comment too. Each style comments only print "An example with single line
comments";

?>

Multi-lines comments − They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary. The multiline style of commenting is the same as in C.
Here are the example of multi lines comments.

<?

/* This is a comment with multiline

Author : Mohammad Mohtashim

Purpose: Multiline Comments Demo

Subject: PHP */

print "An example with multi line comments";

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


39

PHP NOTES FOR MGSU EXAMS GORISH MITTAL

You might also like