0% found this document useful (0 votes)
193 views38 pages

Unit 1

The document discusses the history and advantages of PHP. It covers PHP versions from the original PHP/FI to the current PHP 8. It also discusses server-side programming, the differences between client-side and server-side scripting, and characteristics and advantages of PHP such as being open source, platform independent, simple, and supporting databases.

Uploaded by

Sanket Badave
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)
193 views38 pages

Unit 1

The document discusses the history and advantages of PHP. It covers PHP versions from the original PHP/FI to the current PHP 8. It also discusses server-side programming, the differences between client-side and server-side scripting, and characteristics and advantages of PHP such as being open source, platform independent, simple, and supporting databases.

Uploaded by

Sanket Badave
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/ 38

Unit 1.

Expressions and Control Statements in PHP SVERI


Unit 1.Expressions and control statements in PHP

1.1 History and Advantages of PHP, Syntax of PHP.

1.2 Variables, Data types, Expressions and operators, constants

1.3 Decision making Control statements if, if-else, nested if, switch, break and continue statement.

1.4 Loop control structures:-while, do-while, for and for each

1.1 History and Advantages of PHP:-

History:-

PHP Wasoriginally created by RasmusLerdorf in 1994.write in programs in C with several Common Gateway
he used that PHP code to maintain his personal homepage. He extended them to work with web forms and to
communicate with databases, and called this implementation "Personal Home Page/Forms Interpreter" or
PHP/FI.
PHP/FI could be used to build simple, dynamic web applications. To accelerate bug reporting and improve the
code.
Lerdorf initially announced the release of PHP/FI as "Personal Home Page Tools (PHP Tools) version 1.0"
PHP stands for PHP: Hypertext Preprocessor.
In 1998 PHP 3 the name "Personal Home Page/Forms Interpreter changed to Hypertext Preprocessor
PHP is Open Source Programming Language.
PHP is a server - side scripting language , which means that PHP scripts, or programs, usually run on a Web
server.

PHP Version History


 PHP/FI 2.0 (In June Of 1995)
The parser was largely hand written so often encountered errors.
 PHP 3 (In June, 1998)
Limited object oriented support and a lot of PHP growth.
 PHP 4 (Middle Of 2000)
The most important change made for PHP 4 was the switch to the ZEND engine. More resources used in
PHP scripts like database connection and file.
PHP 4 introduced multi-threading and compile first, execute later.

Prepared By-Mr.Pramod Mane Page 1


Unit 1.Expressions and Control Statements in PHP SVERI
 PHP 5 (In July 2004)
PHP 5 was brought step forward for the language and offered lots of functionalities.
Object oriented support
Improved MySQl Extension
Flat file database SQLite
PDO Extension
Error handling with exception
XML tools
And a lot of features given in PHP 5.
 PHP 6 (In 2005)
Abandoned version of PHP that planned to include native Unicode support
 PHP 7 (In 2014 to 2015)
Object parameter and return type declaration,
Libsodium extension,
abstract method overriding,
parameter type widening.
 PHP 8 (November 26, 2020)
Just-In-Time (JIT) compilation,arrays starting with a negative index,
stricter/saner language semantics (validation for abstract trait methods),
saner string to number comparisons,saner numeric strings,
TypeError on invalid arithmetic/bitwise operators,reclassification of various engine errors,
consistent type errors for internal functions,match expression,union types,mixed type,
static return type, nullsafe operator,non-capturing catches,throw expression

Server Side Programming:-


It is a technique used in Web design which involves embedded scripts in an HTML source code which
results in a Client's request to the Server website being handled by a script/program running Server-Side before
the Server responds to the client request.
Advantages of Server Side Programs:
 All programs reside in one machine called the Server. Any number of Clients can access the server
programs.
 New functionalities to existing programs can be added at the server side.

Prepared By-Mr.Pramod Mane Page 2


Unit 1.Expressions and Control Statements in PHP SVERI
 Migrating to new versions, architectures, design patterns, switching to new databases can be done at the
Server side without having to bother about Clients.
 Issues relating to enter price applications like resource management, concurrency, session management,
security and performance are managed by Server side applications.
 They are portable and possess the capability to generate dynamic and user-based content.
Client vs. Server Side ScriptingLanguage:-

Client Side Scripting Language Server Side Scripting Language

scripts which are especially designed for the client scripts which are especially designed for the server
(Browser) support those scripting language are called support those scripting language are called client side
client side scripting language scripting language

This is not language Secure because source code can This is language Secure because source code can’t
be visible to the user and also we can edit the source visible to the user and also we can’t edit the source
code. code.

This will be executed by the Browser This will be executed by the server

It can’t communicate with database It can communicate with database

Ex.HTML,Javascript,AJAX,Jqueryetc Ex.PHP,JAVA,.NETetc

Why Use PHP:-


 PHP is open source server side scripting language.
 PHP is cross platform.
 PHP is cross database.
 PHP script will execute very fast when compare to other scripting language.(like ASP.NET,Perl,Java)
 PHP is very easy to learn.

Important Coding point about PHP:-


 In PHP there is no need to specify a data types for variable declaration.
 Instead of that ,it can be determined at the time of execution depends on the value of the variable so that
 PHP is called as loosely typed language.
 In PHP every variable need to start with dollar ($) symbol.
 Every statement in PHP must end with semi colon (;).
 PHP support both POP(Procedure Oriented Programming) and OOP(Object Oriented Programming).

Prepared By-Mr.Pramod Mane Page 3


Unit 1.Expressions and Control Statements in PHP SVERI

Characteristics of PHP:-
There are many features given by PHP. All Features discussed below one by one.

1. Familiarity
2. Simplicity
3. Efficiency
4. Security
5. Flexibility
6. Open source
7. Object Oriented

1.Familiarity: -
If you are in programming background then you can easily understand the PHP syntax. And you can
write PHP script because of most of PHP syntax inherited from other languages like C or Pascal.

2.Simplicity: -
PHP provides a lot of pre-define functions to secure your data. It is also compatible with many third-
party applications, and PHP can easily integrate with other.

In PHP script there is no need to include libraries like c, special compilation directives like Java, PHP
engine starts execution from (<?) escape sequence and end with a closing escape sequence (<?). In PHP
script, there is no need to write main function. And also you can work with PHP without creating a class.

3.Efficiency: -
PHP 4.0 introduced resource allocation mechanisms and more pronounced support for object-oriented
programming, in addition to session management features. Eliminating unnecessary memory allocation.

4.Security: -
Several trusted data encryption options are supported in PHP’s predefined function set. You can use a
lot of third-party applications to secure our data, allowing for securing our application.

5.Flexibility: -

You can say that PHP is a very flexible language because of PHP is an embedded language you can
embed PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many others. You can run your PHP
script any device like mobile Phone, tabs, laptops, PC and other because of PHP script execute on the server
then after sending to the browser of your device.

Prepared By-Mr.Pramod Mane Page 4


Unit 1.Expressions and Control Statements in PHP SVERI

6.Free: -
PHP is an open source programming language so you can download freely there is no need to buy a
license or anything.

7.Object Oriented: -
PHP has added some object-oriented programming features, and Object Oriented programming became
possible with PHP 4. With the introduction of PHP 5, the PHP developers have really beefed up the object-
oriented features of PHP, resulting in both more speed and added features.

Advantages of PHP:-
Following are some important advantages of PHP which are as follows:
1. Open Source
2. Platform Independent
3. Simple and Easy
4. Database
5. Fast
6. Maintenance
7. Support:
8. Testing
9. Security
10. Stable
1. Open Source:-
PHP is open-source and free of cost, which helps developers to install it quickly and readily available for
use. There are a lot of PHP frameworks and developer can choose any of the frameworks to work. All the
features and tools will be provided to the developer for that framework easily. As it is open-source, it makes
the system ready with PHP in quick time and makes the web development faster with the help of providing
the tools and other features easily.
2. Platform Independent:-
PHP is mainly supported by all the operating systems like Windows, Unix, Linux etc. The PHP based
developed web applications can be easily run on any platform. It can be integrated with other programming
language and database easily and there is no requirement of re-development. It helps in saving a lot of effort
and cost.
3. Simple and Easy:-
This advantage of PHP is simple and easy to learn and code. It is mainly organized code and clean,
which helps the new developers also. The command functions of PHP can easily learn and understood. The

Prepared By-Mr.Pramod Mane Page 5


Unit 1.Expressions and Control Statements in PHP SVERI
one who knows any programming language can easily work on PHP. It is simple to learn, as its learning curve
is not large. The syntax is simple and flexible to use.
4. Database:-
PHP is easily connected with the database and make the connection securely with databases. It has a
built-in module that is used to connect to the database easily. There are many web applications, which require
strong programming language with a good database management system. PHP and its database
connection solve the purpose for development of web applications. It reduces the time to connect to a
database management system as well. Multiple databases can be integrated with PHP.
5. Fast:-
PHP is known as the fastest Programming language as compared to another. PHP applications can be
easily loaded over the slow Internet and data speed. Other applications take a lot of time to connect the
database and fetch the data after executing certain queries to the database. PHP does not face this problem and
it loads the website very easily and fast. The fast speed of PHP provides the developer with an edge to
develop the web applications in PHP programming language.
6. Maintenance:-
PHP framework is mainly used to make the web application development easier and maintain the code
automatically. The model view controller architecture in PHP framework helps the code to be easily
maintained and used. The MVC architecture helps the separation of a file for different module separately.
7. Support:-
This advantage of PHP has great online support and community, which helps the new developers to help
in writing the code and developing the web applications. The documentation provided at the official site helps
in using the different features of PHP and its framework. The latest updates are released timely by the PHP to
make it better for the developer to develop the web-based applications.
8. Testing:-
PHP based web applications can be easily tested. PHP unit uses to perform the unit testing quickly and
easily. It also helps the programmers to write test cases and perform the testing smoothly. For PHP based web
applications, the developers do not need to write the additional code. PHP frameworks help in automating the
different tasks.
9. Security:-
PHP frameworks built-in feature and tools make it easier to protect the web applications from the outer
attacks and security threats. The security threats can be like SQL injection, data tampering, and forgery etc.
To protect from these security threats, developers used PHP frameworks for developing web applications.
10. Stable:-
PHP is also stable as compared to other programming languages. It has been in existence for a long time.
The developers have worked on PHP to make it easy for the programmers to work on developing the PHP
web-based applications. They have fixed the issues and bugs over the period of time for the different version
of PHP and make it very stable.

Prepared By-Mr.Pramod Mane Page 6


Unit 1.Expressions and Control Statements in PHP SVERI
Syntax of PHP:-

A PHP script can be placed anywhere in the document.

A PHP script starts with <? php and ends with ?>:

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

<?php

// PHP code goes here

?>

Example:-

<html>
<body>

<h1>My first PHP page</h1>

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

</body>
</html>

Prepared By-Mr.Pramod Mane Page 7


Unit 1.Expressions and Control Statements in PHP SVERI
1.2 Variables, Data types, Expressions and operators, constants:-
Variables:-

What is Variables?
It is reference name for the data
By using Variables we can store data/information to use in future program.
How to declare /Initialize variable in PHP:-
To declare we have to use $ symbol
Syntax:-$variablename;
Example:-
$a; $b; $A; $value; $Roll_no;
$Student_name; $Count;

Initialize variable in PHP:-


Syntax:-$variablename=value;
$a=10; $b=20; $A=40; $value=5;
$Roll_no=01;
$Student_name=”Pramod”; $Count=0;
Rules to declare Variables in PHP-

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

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)

Prepared By-Mr.Pramod Mane Page 8


Unit 1.Expressions and Control S
Statements
tatements in PHP SVERI
Program1.write a program to add two numbers?

<?php

$a = 5;

$b = 6;

$txt1="Addition of a and b ";

echo $txt1
$txt1;

$sum=$a + $b;

echo $sum;

?>

Program2.write
.write a program to performarithmeticoperations?

<?php

$a = 16;

$b = 8;

$="Addition
Addition of a and b ";

echo "$txt1 <br>";

$sum=$a + $b;

echo $sum;

echo "<br>";

Prepared By-Mr.Pramod Mane Page 9


Unit 1.Expressions and Control Statements in PHP SVERI
$txt1="Subtraction of a and b ";

echo "$txt1 <br>";

$sub=$a - $b;

echo $sub;

echo "<br>";

$txt1="Multiplication of a and b ";

echo "$txt1 <br>";

$mul=$a * $b;

echo $mul;

echo "<br>";

$txt1="Division of a and b ";

echo "$txt1 <br>";

$div=$a / $b;

echo $div;

echo "<br>";

?>

Prepared By-Mr.Pramod Mane Page 10


Unit 1.Expressions and Control Statements in PHP SVERI
Output:-

Comments in PHP:-

 Syntax for single-line comments:

Use // OR #

Example :-

<!DOCTYPE html>
<html>
<body>

<? php
echo "Computer Department";

# echo "Civil Department";

// echo "Mech Department";


?>

</body>
</html>

Output: -Computer Department

Prepared By-Mr.Pramod Mane Page 11


Unit 1.Expressions and Control Statements in PHP SVERI
 Syntax for multiple-line comments:

/* */

Example :-

<!DOCTYPE html>
<html>
<body>

<? php
echo "Computer Department";

/* echo "Civil Department";

echo "Mech Department";

*/
?>

</body>
</html>

Output: - Computer Department

PHP Data Types

PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can
be categorized further in 3 types:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

1.Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

1. Boolean
2. integer
3. float
4. string

2.Compound Types

Prepared By-Mr.Pramod Mane Page 12


Unit 1.Expressions and Control Statements in PHP SVERI
It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

3.Special Types

There are 2 special data types in PHP.

1. resource
2. NULL

1.Boolean

Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is
often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.

2.Integer

Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without
fractional part or decimal points.

Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.

Example:

<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>

Prepared By-Mr.Pramod Mane Page 13


Unit 1.Expressions and Control Statements in PHP SVERI
Output:

Decimal number: 34
Octal number: 163
HexaDecimal number: 69

3.Float

A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional
or decimal point, including a negative or positive sign.

Example:

<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

Output:

Addition of floating numbers: 73.812

4.String

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.

String values must be enclosed either within single quotes or in double quotes. But both are treated differently.
To clarify this, see the example below:

Example:

<?php
$company = "SPC";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>

Prepared By-Mr.Pramod Mane Page 14


Unit 1.Expressions and Control Statements in PHP SVERI
Output:

Hello SPC
Hello $company

1.Array

An array is a compound data type. It can store multiple values of same data type in a single variable.

Example:

<?php

$bikes = array ("Unicorn", "Passion", "Splender");

var_dump($bikes);

//the var_dump() function returns the datatype and values

echo "</br>";

echo "Array Element1: $bikes[0] </br>";

echo "Array Element2: $bikes[1] </br>";

echo "Array Element3: $bikes[2] </br>";

?>

Output:

array(3) { [0]=> string(7) "Unicorn" [1]=> string(7) "Passion" [2]=> string(8) "Splender" }
Array Element1: Unicorn
Array Element2: Passion
Array Element3: Splender

Prepared By-Mr.Pramod Mane Page 15


Unit 1.Expressions and Control Statements in PHP SVERI

2.object

Objects are the instances of user-defined classes that can store both values and functions. They must be
explicitly declared.

Example:

<?php
class bike {
function model()
{
$model_name = "Unicorn";
echo "Bike Model: ";
echo $model_name;
}
}
$obj = new bike();
$obj -> model(); //->
?>
Output:
Bike Model: Unicorn

1.Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references
to external PHP resources. For example - a database call. It is an external resource.

2.Null

Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as
it is case sensitive
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

Prepared By-Mr.Pramod Mane Page 16


Unit 1.Expressions and Control Statements in PHP SVERI

PHP Expressions

Introduction
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

expression with ++ and -- operators


These operators are called increment and decrement operators respectively. They are unary operators, needing
just one operand and can be used in prefix or postfix manner, although with different effect on value of
expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements by 1).
However, when used in assignment expression, prefix makesincremnt/decrement first and then followed by
assignment. In case of postfix, assignment is done before increment/decrement
Uses postfix ++ operator
Example

<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
Output
This produces following result

x = 11 y = 10
Whereas following example uses prefix increment operator in assignment

Prepared By-Mr.Pramod Mane Page 17


Unit 1.Expressions and Control Statements in PHP SVERI
Example

<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
Output
This produces following result

x = 11 y = 11

Expression with Ternary conditional operator


Ternary operator has three operands. First one is a logical expression. If it is TRU, second operand expression is
evaluated otherwise third one is evaluated
Example

<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>

Output
Following result will be displayed

pass

Prepared By-Mr.Pramod Mane Page 18


Unit 1.Expressions and Control Statements in PHP SVERI

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 Try it »

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y Try it »

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

** Exponentiation $x ** $y Result of raising $x to the $y'th Try it »


power

Prepared By-Mr.Pramod Mane Page 19


Unit 1.Expressions and Control Statements in PHP SVERI
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 Try it »

x -= y x=x–y Subtraction

x *= y x=x*y Multiplication Try it »

x /= y x=x/y Division

x %= y x=x%y Modulus Try it »

Prepared By-Mr.Pramod Mane Page 20


Unit 1.Expressions and Control Statements in PHP SVERI
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 are of Try
the same type it »

!= 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 Try


it »

!== 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 Try


it »

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

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

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


equal to

Prepared By-Mr.Pramod Mane Page 21


Unit 1.Expressions and Control Statements in PHP SVERI

<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater Try
than zero, depending on if $x is less than, equal it »
to, or greater than $y. Introduced in PHP 7.

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 Name Description

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

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

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

$x-- Post-decrement Returns $x, then decrements $x by one Try it »

Prepared By-Mr.Pramod Mane Page 22


Unit 1.Expressions and Control Statements in PHP SVERI

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

or Or $x or $y True if either $x or $y is true Try it »

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 Try it »

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

! Not !$x True if $x is not true Try it »

Prepared By-Mr.Pramod Mane Page 23


Unit 1.Expressions and Control Statements in PHP SVERI
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 Try it »


assignment

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 Try it


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 Try it


»

Prepared By-Mr.Pramod Mane Page 24


Unit 1.Expressions and Control Statements in PHP SVERI

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

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


identity »

PHP Conditional Assignment Operators

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

Operator Name Example Result

?: Ternary $x Returns the value of $x.


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

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


coalescing 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.
Introduced in PHP 7

Prepared By-Mr.Pramod Mane Page 25


Unit 1.Expressions and Control Statements in PHP SVERI

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant

To create a constant, use the define() function.

Syntax:-
define (name, value, case-insensitive)

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
 Default is false

Program1:-

<?php

define("Message", "Your are in Computer Department");


echo Message;

?>

Output:-

Your are in Computer Department

Prepared By-Mr.Pramod Mane Page 26


Unit 1.Expressions and Control Statements in PHP SVERI
Program2:-Create an Array constant

<?php

define("student_name", ["Ram","Sham","Sita","Gita"]);

echo student_name[3];

?>
Output:- Gita

Prepared By-Mr.Pramod Mane Page 27


Unit 1.Expressions and Control Statements in PHP SVERI
1.3 Decision Making Control Statements:-

1.if
2.if-else
3.netsed if
4.swtich
5.Break
6.Continue
1. The if Statement:-

The if statement executes some code if one condition is true.

Syntax
if (check condition)

if condition is true then code to be executed;

Program:-

<?php
$a =10;
$b =20;
if ($a < $b)
{
echo "Value of a less then b";
}
?>

Output:-

Prepared By-Mr.Pramod Mane Page 28


Unit 1.Expressions and Control Statements in PHP SVERI
2.The if...else Statement:-

Syntax
if (Check condition)

{
if condition is true then code to be executed;

} else

{
if condition is false then code to be executed;

Program:-

<?php
$a =50;
$b =10;
if ($a < $b)
{
echo "Value of a less then b";
}
else
{
echo "Value of a Greater then b";
}
?>

Output:-

Prepared By-Mr.Pramod Mane Page 29


Unit 1.Expressions and Control Statements in PHP SVERI
3.The if...elseif...else Statement

Syntax
if (condition)

{
if condition is true then code to be executed;
} elseif (condition)

{
if first condition is false and this condition is true code to be executed;
} else

{
if all conditions are false code to be executed;
}

Program:-

<?php
$a =40;
$b =40;
if ($a < $b)
{
echo "Value of a less then b";
}
elseif($a > $b)
{
echo "Value of a Greater then b";
}

else
{
echo "Value of a and b are Equal ";
}
?>

Prepared By-Mr.Pramod Mane Page 30


Unit 1.Expressions and Control Statements in PHP SVERI
Output:-

4.The switch Statement:-

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n)
{
case label1:
if n=label1code to be executed;
break;
case label2:
if n=label2 code to be executed;
break;
case label3:
if n=label3 code to be executed;
break;
...
default:
if n is different from all labels code to be executed;
}

Program:-

<?php
$student = 1;
switch ($student)

{
case "1":
echo "My Name is Ram and Roll No is 1";
break;
case "2":
echo "My Name is Sham and Roll No is 2";

Prepared By-Mr.Pramod Mane Page 31


Unit 1.Expressions and Control Statements in PHP SVERI
break;
case "3":
echo "My Name is Gita and Roll No is 3";
break;
default:
echo "Student is not Present in Class";
}
?>

Output:-

5.Break:-

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

Below example break the loop when x is equal to 5

Program:-
<?php

for ($x = 1; $x < 10; $x++) {

if ($x == 5) {

break;

echo "Presnt Roll No is: $x <br>";

?>

Prepared By-Mr.Pramod Mane Page 32


Unit 1.Expressions and Control Statements in PHP SVERI
Output:-

6.Continue :-

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

This example skips the value of 5:

Program:-
<?php
$x = 1;
while($x < 10) {
if ($x == 5) {
$x++;
continue;
}
echo "Presnt Roll No is: $x <br>";
$x++;
}
?>
Output:-

Prepared By-Mr.Pramod Mane Page 33


Unit 1.Expressions and Control Statements in PHP SVERI

1.4 Loop control structures:-while, do-while, for and for each

Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

1 while - loops through a block of code as long as the specified condition is true
2 do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
3 for - loops through a block of code a specified number of times
4 foreach - loops through a block of code for each element in an array

1.while Loop

The while loop - Loops through a block of code as long as the specified condition is true.

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition is true) {
code to be executed;
}

Examples

The example below displays the Roll No from 1 to 10:

Example
<?php
$x = 1;

while($x <= 10) {


echo "Roll no is: $x <br>";
$x++;
}
?>

Prepared By-Mr.Pramod Mane Page 34


Unit 1.Expressions and Control Statements in PHP SVERI

3.do...while Loop

The do...while loop - Loops through a block of code once, and then repeats the loop as long as the specified
condition is true.

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the
loop while the specified condition is true.

Syntax
do

{
code to be executed;
} while (condition is true);

Example
<?php
$x = 1;

do {
echo "Roll No is: $x <br>";
$x++;
} while ($x <= 10);
?>

Prepared By-Mr.Pramod Mane Page 35


Unit 1.Expressions and Control Statements in PHP SVERI

Note: In a do...while loop the condition is tested AFTER executing the statements within the loop.

do...while loop will execute its statements at least once,

even if the condition is false.

3.for Loop

The for loop - Loops through a block of code a specified number of times.

The for loop is used when you know in advance how many times the script should run.

Syntax
for (init counter; test counter; increment counter)

{
code to be executed for each iteration;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates
to FALSE, the loop ends.
 increment counter: Increases the loop counter value

Prepared By-Mr.Pramod Mane Page 36


Unit 1.Expressions and Control Statements in PHP SVERI
The example below displays the Student Roll No from 1 to 10:

Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "Roll No is: $x <br>";
}
?>

4.foreach Loop

The foreach loop - Loops through a block of code for each element in an array.

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax
foreach ($array as $value)

{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is
moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Prepared By-Mr.Pramod Mane Page 37


Unit 1.Expressions and Control Statements in PHP SVERI
Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

Prepared By-Mr.Pramod Mane Page 38

You might also like