0% found this document useful (0 votes)
6 views79 pages

Unit 1 Iwd

Unit-I provides an introduction to PHP, covering topics such as static and dynamic websites, PHP syntax, output statements, variables, constants, and operators. It explains the features and history of PHP, including its ability to generate dynamic content and interact with databases. The document also details PHP's variable scope, constants, and magic constants, along with examples and syntax for better understanding.

Uploaded by

project.honest30
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)
6 views79 pages

Unit 1 Iwd

Unit-I provides an introduction to PHP, covering topics such as static and dynamic websites, PHP syntax, output statements, variables, constants, and operators. It explains the features and history of PHP, including its ability to generate dynamic content and interact with databases. The document also details PHP's variable scope, constants, and magic constants, along with examples and syntax for better understanding.

Uploaded by

project.honest30
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/ 79

Unit-I

Introduction to PHP

Topics
1.1 Introduction to Static and Dynamic Websites
1.2 Introduction to PHP and it’s History
1.3 Basic PHP syntax and file structure
1.4 Output statements: echo and print
1.5 PHP variables and value types
1.6 PHP Constants and magic constants
1.7 PHP Operators and their precedence:
i. Arithmetic operators
ii. Increment-decrement operators
iii. Assignment operators
iv. Logical operators
v. Bitwise operators
vi. Comparison operators
1.8 Decision-making statements: if statement, if-else statement, else-if clause, switch-case
statement, the ? operator
1.9 Loops: while loop, for loop, foreach loop, nesting loops
1.10 Break and continue statements
1.1
Introduction to static and Dynamic websites
Static website
• A static website is made up of webpages
created using HTML,CSS and Javascript etc.
Dynamic website
• Dynamic website is a collection of dynamic
web pages whose content changes
dynamically.

• Static website

https://www.geeksforgeeks.org/static-vs-dynamic-website/
• Dynamic website

Static vs Dynamic website


Content of Web pages can not be change Content of Web pages can be
at runtime. changed.

No interaction with database possible. Interaction with database is


possible

It is faster to load as compared to It is slower than static website.


dynamic website
Server-side languages such as
HTML, CSS etc is used for developing PHP, JSP etc are used.
the website.
Content Management System
Flexibility is the main advantage of static (CMS) is the main advantage of
website dynamic website.

Cheaper Development costs. More Development costs.


1.2
Introduction to PHP and it‟s History

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
• PHP is free to download and use

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
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 easy to learn and runs efficiently on the
server side

What is a PHP File?


• PHP files can contain text, HTML, CSS,
JavaScript, and PHP code
• PHP code are executed on the server, and the
result is returned to the browser as plain
HTML
• PHP files have extension ".php"
Features of PHP
• Open Source – Free to download & use (No license required)
– www.php.net

• Platform independent (Windows, Linux, Unix, Mac OS X, etc.)

• Compatible with almost all servers (Apache, IIS, etc.)

• Supports a wide range of databases

• Easily integrated with HTML, CSS & JavaScript


• POP as well as OOP support

• Easy to output HTML as well as XHTML & XML content

• Output can also be in the form of images, PDF files, flash movies, etc.

• Easy to learn as a beginner and also powerful enough to manage a social


networking website (Facebook)

History of PHP
• Timeline for different major versions of PHP:
1.3
Basic PHP syntax and File structure

• A PHP script starts with


<?php and ends with ?>

<?php //start of php code


// PHP code goes here
?> // end of php code

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

• A PHP file contains HTML tags, and some PHP


scripting code.

• PHP script that uses a built-in PHP function "echo" to


output the text "Hello World!" on a web page:
• <html>
<body>
<h1>My first PHP page</h1>
<? Php
echo "Hello World!";
?>
</body>
</html>
• PHP statements end with a semicolon (;).

Result:- My first PHP page


Hello World!

• Comments in php
A comment in PHP code is a line that is not
read/executed as part of the program. Its only
purpose is to be read by someone who is
looking at the code.
• <html> <body>
<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body></html>
• Result is :- 10

Working of PHP
• Type php code in any text editor..

• Save the file by „.php‟ extension in specific folder:


– In „C:\xampp\htdocs‟ folder, if you have installed xampp
– In „C:\wamp\www‟ folder, if you have installed wamp

– NOTE: Here, C is assumed as the installation folder. It will


be different if you have installed xampp/wamp elsewhere

• Open the file in the browser through the local server


(localhost) by typing: „localhost/filename.php‟
• If there is no error, you will see the output of
the php code, else you will see the error.

• But before running the php file, make sure


your web server is running

• To check if the server is running without error,


simply type localhost in the browser to see if
the xampp / wamp home page opens

1.4 Output statements: echo and print

In PHP there are two basic ways to get output:


echo and print
echo and print are more or less the same.
They are both used to output data to the screen.
• echo – will output whatever is written in quotes, in the browser
• print command can also be used to print the output in place of
echo

• echo vs print:
– echo has no return value, while print has a return value of 1
– echo is marginally faster than print
– echo can take multiple parameters, while print takes only
one
The PHP print Statement
• The print statement can be used with or
without parentheses: print or print().
Display Text
• The following example shows how to output
text with the print command (notice that the
text can contain HTML markup):

<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

Result:- PHP is Fun!


Hello world!
I'm about to learn PHP!
Display Variables
• The following example shows how to output text and variables with the print statement:

<?php
$txt1 = "Learn PHP";
$txt2 = ”My Sql";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP and " . $txt2 . "<br>";
print $x + $y;
?>
Result:- Learn PHP
Study PHP and My Sql
9

The PHP echo Statement


• The echo statement can be used with or
without parentheses: echo or echo().
Display Text
• The following example shows how to output
text with the echo command (notice that the
text can contain HTML markup):
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple
parameters.";
?>

Result:- PHP is Fun!


Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.

• Display Variables
• The following example shows how to output text and variables with the echo statement:

<?php
$txt1 = "Learn PHP";
$txt2 = “My Sql";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP and " . $txt2 . "<br>";
echo $x + $y;
?>
• Result:- Learn PHP
Study PHP and My Sql
9
1.5 PHP Variable and value types
Variables are "containers" for storing information.
• Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the
variable:
• 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)

#note: Remember that PHP variable names are case-sensitive

Output Variables
• The PHP echo statement is often used to
output data to the screen.

<? php
$txt = “Computer Game";
echo "I like $txt!";
?>

Result:-I like Computer Game!


• The following example will produce the same
output as the example above:
<html>
<body>
<?php
$txt = ”Computer Game “;
echo "I like " . $txt . "!";
?>
</body>
</html>

Result:-I like Computer Game!

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>

Result : Hello world!


5
10.5
• The following example will output the sum of two variables:

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

• Result:- 9

PHP Variables Scope


• In PHP, variables can be declared anywhere in the
script.
• The scope of a variable is the part of the script
where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static
• Global variable: A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function:
<?php
$x=5;
function myTest()
{
// Using $x directly inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
// Error: Undefined variable $x in this scope
}
myTest(); // Calls the function
// $x is accessible here as it is in the global scope
echo "<p>Variable x outside function is: $x</p>";
?>

• Local scope: A variable declared within a function has a


LOCAL SCOPE and can only be accessed within that
function:
<?php
function myTest()
{
$x = 5; // Local variable, only accessible within this function
echo "<p>Variable x inside function is: $x</p>";
}
myTest(); // Calls the function
// Attempt to access $x outside the function
echo "<p>Variable x outside function is: $x</p>";
?>
PHP The global Keyword
• The global keyword is used to access a global variable from
within a function. To do this, use the global keyword
before the variables (inside the function):
<?php
$x = 5; // Global variable
$y = 10; // Global variable
function myTest()
{
global $x, $y; // Bring the global variables $x and $y into the
function
$y = $x + $y; // Modify $y by adding $x to it
}
myTest(); // Calls the function
echo $y; // Outputs the modified value of $y
?>

Static keyword: when a function is completed/executed,


all of its variables are deleted. If we want not to be deleted, use
the static keyword when you first declare the variable.
<?php
function test()
{
static $x = 0; // Static variable, initialized only once
echo $x; // Prints the current value of $x

$x++; // Increments $x

}
test(); // First function call

test(); // Second function call

test(); // Third function call

?>
1.6 PHP Constants and magic constants
• Constants are like variables, except that once they are
defined, they cannot be changed or undefined.

• A valid constant name starts with a letter or underscore,


but (NO $ sign before the constant name).

• Unlike variables, constants are automatically global


across the entire script..

• Constants can be made using the define( ) function or


const keyword.

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


– name: Specifies the name of the constant
– value: Specifies the value of the constant
– case-insensitive is optional. Its default value is
false.
– e.g. define(PI, 3.14);
• Syntax: const name = value;
– e.g. const PI = 3.14;
• Create a constant with a case-sensitive name:

<?php
// case-sensitive constant name
define("HOME", "Welcome!");
echo HOME;
?>

Result: Welcome!

• Create a constant with a case-insensitive name:

<?php
// case-insensitive constant name
define("HOME", "Welcome!", true);
echo home;
?>
Result: Welcome!

*Names are case-sensitive by default, but you can make them


case-insensitive
<?php
// case-insensitive constant name
define("HOME", "Welcome!");
echo home;
?>
o/p: home

• const keyword
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.

<?php
const MESSAGE="Hello PHP";
echo MESSAGE;
?>
Result: Hello PHP
• Constants are Global
Constants are automatically global and can be used
across the entire script.
<?php
define("GREAT", "INDIA");
function myTest() {
echo GREAT;
}
myTest();
?>
Result: INDIA

const vs. define()

const are always case-sensitive


define() has a case-insensitive option.

const cannot be created inside another block scope, like


inside a function or inside an if statement.
define can be created inside another block scope.
Predefined (Magic) Constants in PHP
It is predefined constants that change value depending on where they are used,
and therefor they are called "magic constants".

__LINE__
• It returns the current line number of the file,
where this constant is used.

<?php
echo "<h3>Example for __LINE__</h3>";
// print Your current line number i.e;4
echo "You are at line number " . __LINE__ . "<br><br>";
?>

O/P:
Example for __LINE__
You are at line number 4
__FILE__
• This magic constant return the full path of the
executed file with the name of the file.

<?php
echo "The file name is : “ . __FILE__;
?>
O/P:
The file name is : C:\xampp\htdocs\test.php

__DIR__
The directory of the file.
<?php
echo __DIR__;
?>
O/P:
C:\xampp\htdocs
__FUNCTION__
If inside a function, the function name is returned.
<?php
function myValue()
{
return __FUNCTION__;
}
echo myValue();
?>
O/P: myValue

__CLASS__
If used inside a class, the class name is returned.
<?php
class Fruits {
public function myValue(){
return __CLASS__;
}
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
O/P: Fruits
__METHOD__
If used inside a function that belongs to a class, both
class and function name is returned.
<?php
class Fruits {
public function myValue() {
return __METHOD__;
}
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
O/P:
Fruits::myValue

__NAMESPACE__
If used inside a namespace, the name of the
namespace is returned.
<?php
namespace myArea;
function myValue()
{
return __NAMESPACE__;
}
?>
<?php
echo myValue();
?> O/P: myArea
Data types
Variables can store data of different types, and
different data types can do different things.
• PHP Integer
• PHP Float
• PHP Boolean
• PHP NULL Value
• PHP String
• PHP Array
• PHP Object

R.P.Vasava

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
R.P.Vasava
• PHP integer
• In the following example
$x is an integer.
• The var_dump() function
is a built-in function of
PHP.
• The PHP var_dump()
function returns the data
type and value of the
variable.
• In case of string ,it also
includes the size of the
string passed inside the
function.
• Syntax:
var_dump(var1,var2….);
R.P.Vasava

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:

R.P.Vasava
PHP Boolean
• A Boolean represents two possible states: TRUE
or FALSE.
Ex: $x = true;
$y = false;
<?php <?php
$x=10; $x=TRUE;
$y=20; Echo $x;
var_dump($x>$y);
?> o/p: 1
o/p: bool(false)

R.P.Vasava

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.

R.P.Vasava
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:
<?php
$x = "Hello world!";
var_dump($x);
?>

o/p: string(12) "Hello world!"

R.P.Vasava

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:

R.P.Vasava
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.
• 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. A Car 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.
R.P.Vasava

R.P.Vasava
PHP Operators
• Operators are used to perform operations on variables
and values.

PHP divides the operators in the following groups:


i. Arithmetic operators
ii. Logical operators
iii. Bitwise operators
iv. Assignment operators
v. Comparison operators
vi. Increment/Decrement operators
vii. String operators
viii. Conditional (Ternary) Operator
R.P.Vasava

• PHP Arithmetic Operators


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

R.P.Vasava
• Arithmetic operator
<?php
$a = 10;
$b = 3;

// Addition
echo $a + $b . "<br>"; // Output: 13

// Subtraction
echo $a - $b . "<br>"; // Output: 7

// Multiplication
echo $a * $b . "<br>"; // Output: 30

// Division
echo $a / $b . "<br>"; // Output: 3.3333333333333

// Modulus
echo $a % $b . "<br>"; // Output: 1

// Exponentiation
echo $a ** $b . "<br>"; // Output: 1000
?> R.P.Vasava

• Logical operators
• The PHP logical operators are used to combine
conditional statements.

R.P.Vasava
• Logical AND
<?php
$x = 100;
$y = 50;
if ($x == 100 and $y == 50)
{
echo "Hello world!";
}
?>

O/P: Hello world!


R.P.Vasava

• Logical OR

<?php
$x = 100;
$y = 50;

if ($x == 100 or $y == 80)


{
echo "Hello world!";
}
?>

o/p: Hello world!

R.P.Vasava
• Logical AND (&&)

<?php
$x = 100;
$y = 50;

if ($x == 100 && $y == 50)


{
echo "Hello world!";
}
?>

o/p: Hello world!

R.P.Vasava

• Logical OR(||)

<?php
$x = 100;
$y = 50;

if ($x == 100 || $y == 80)


{
echo "Hello world!";
}
?>

o/p: Hello world!


R.P.Vasava
• Logical not(!)

<?php
$x = 100;

if (!($x == 90))
{
echo "Hello world!";
}
?>

o/p:Hello world!

R.P.Vasava

• Logical XOR

<?php
$x = 100;
$y = 50;

if ($x == 100 xor $y == 80)


{
echo "Hello world!";
}
?>

o/p: Hello world!

R.P.Vasava
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.

R.P.Vasava

• Assignment operator

R.P.Vasava
• Ex: x = y

<?php
$x = 10;
echo $x;
?>

o/p: 10

R.P.Vasava

Ex: x += y

<?php
$x = 20;
$x += 100;

echo $x;
?>

o/p: 120
R.P.Vasava
• Ex: x -= y

<?php
$x = 50;
$x -= 30;

echo $x;
?>

o/p: 20
R.P.Vasava

• Ex: x *= y

<?php
$x = 5;
$x *= 6;

echo $x;
?>

o/p: 30

R.P.Vasava
• Ex: x /= y

<?php
$x = 10;
$x /= 5;

echo $x;
?>

o/p: 2

R.P.Vasava

• Ex: x %= y

<?php
$x = 15;
$x %= 4;

echo $x;
?>

o/p: 3

R.P.Vasava
• Comparison Operators
The PHP comparison operators are used to
compare two values (number or string):

R.P.Vasava

Equal ==

<?php <?php
$x = 100; $x = 100;
$y = 100; $y = “100”;

var_dump($x == $y); var_dump($x == $y);


?> ?>

o/p: bool(true) o/p: bool(true)

R.P.Vasava
Identical ===

<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>

o/p: bool(false)

:It checks whether two variables have the same value and
are of the same type.
R.P.Vasava

Not equal != Not equal !=

<?php <?php
$x = 100; $x = 100;
$y = 50; $y = “100”;

var_dump($x != $y); var_dump($x != $y);


?> ?>

o/p: bool(true) o/p: bool(false)


R.P.Vasava
Not equal <>
<?php
$x = 100;
$y = 100;

var_dump($x <> $y); // returns false because values are equal


?>

o/p: bool(false)
R.P.Vasava

Not identical !==

<?php
$x = 100;
$y = "100";

var_dump($x !== $y); // returns true because types are not equal
?>

o/p: bool(true)

:In this example, even though $x and $y have the same value, they are
of different types (integer vs. string), so !== returns true.
R.P.Vasava
Greater than >

<?php
$x = 100;
$y = 50;

var_dump($x > $y); // returns true because $x is greater than $y


?>

o/p: bool(true)

R.P.Vasava

Less than <

<?php
$x = 10;
$y = 50;

var_dump($x < $y); // returns true because $x is less than $y


?>

o/p: bool(true)

R.P.Vasava
Greater than or equal to >=

<?php
$x = 50;
$y = 50;

var_dump($x >= $y); // returns true because $x is greater than or equal to $y


?>

o/p: bool(true)

R.P.Vasava

Less than or equal to <=

<?php
$x = 50;
$y = 50;

var_dump($x <= $y); // returns true because $x is less than or equal to $y


?>

o/p: bool(true)

R.P.Vasava
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.

R.P.Vasava

++$x Pre-increment

<?php
$x = 10;
echo $x ."</br>";
echo ++$x;
?>

o/p: 10
11
R.P.Vasava
$x++ Post-increment

<?php
$x = 10;
echo $x."</br>";
echo $x++."</br>";
echo $x;
?>

o/p: 10
10
11
R.P.Vasava

--$x Pre-decrement

<?php
$x = 10;
echo $x."</br>";
echo --$x;
?>

o/p: 10
9

R.P.Vasava
$x-- Post-decrement

<?php
$x = 10;
echo $x; o/p: 10
echo "</br>"; 10
9
echo $x--;
echo "</br>";
echo $x;
?>
R.P.Vasava

Example:
<?php
$x = 5;
$y = 10;
$z = ++$x + $y-- - $x++ * --$y;
echo $z;
?>

o/p: -32

R.P.Vasava
• Bitwise operators
The Bitwise operators is used to perform bit-level
operations on the operands. The operators are first
converted to bit-level and then calculation is performed on
the operands.

R.P.Vasava

& (Bitwise AND)


Bitwise AND operator in PHP takes two numbers as operands and
does AND on every bit of two numbers. The result of AND is 1
only if both bits are 1.

| (Bitwise OR)
Bitwise OR operator takes two numbers as operands and does OR
on every bit of two numbers. The result of OR is 1 any of the two
bits is 1.

^ (Bitwise XOR )
This is also known as Exclusive OR operator. Bitwise XOR takes
two numbers as operands and does XOR on every bit of two
numbers.

R.P.Vasava
~ (Bitwise Complement)
Add 1 to the given number and change the sign

<< (Bitwise Left Shift)


Bitwise Left Shift operator takes two numbers, left shifts
the bits of the first operand, the second operand decides the
number of places to shift.(Note: Bitwise left shift with one
bit is equivalent to multiplication with 2)

>> (Bitwise Right Shift)


Bitwise Right Shift operator takes two numbers, right shifts
the bits of the first operand, the second operand decides the
number of places to shift.(Note: Bitwise right shift with one
bit is equivalent to division with 2)

R.P.Vasava

<?php
$x = 5;
o/p:
$y = 3;
// Bitwise AND
Bitwise & of 5 and 3 is 1
$z = $x & $y;
echo "Bitwise & of 5 and 3 is“ . $z . "<br>";
// Bitwise OR Bitwise | of 5 and 3 is 7
$z = $x | $y;
echo "Bitwise | of 5 and 3 is“ . $z . "<br>";
// Bitwise XOR Bitwise ^ of 5 and 3 is 6
$z = $x ^ $y;
echo "Bitwise ^ of 5 and 3 is" . $z . "<br>";
// Bitwise NOT Bitwise ~ of 5 is -6
$z = ~$x;
echo "Bitwise ~ of 5 is“ . $z. "<br>";
// Bitwise Left shift 5 << 1 will be 10
$y = 1;
$z = $x << $y;
echo "5 << 1 will be“ . $z . "<br>";
// Bitwise Right shift 5 >> 1 will be 2
$z = $x >> $y;
R.P.Vasava
echo "5 >> 1 will be“ . $z . "<br>"; ?>
R.P.Vasava

String operators
There are two string operators.

R.P.Vasava
• Concatenation

<?php
$txt1 = "Hello"; o/p: Hello world!
$txt2 = "world!";
echo $txt1 . $txt2;
?>

R.P.Vasava

• Concatenation assignment

<?php
o/p: Hello world!
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>

R.P.Vasava
• Conditional (Ternary) Operator
The ternary operator is a simplified conditional
operator like if / else.
Syntax:
condition ? <expression if true> : <expression if false>
<?php
$age = 20;
print ($age >= 18) ? "Adult" : "Not Adult";
?>
o/p:Adult

R.P.Vasava

• Knowing a Variable’s Data Type


2 ways to know/print a variable’s data type:

– gettype( ) function:
• Syntax: gettype(variable_name);
• Example: $x = 2.5;
echo gettype($x); // Output: double

– var_dump( ) function:
• Syntax: var_dump(variable_name);
• Example: $x = 10;
var_dump($x); // Output: int(10)  datatype(value)
• Example: $y = “hi”;
var_dump($y); // Output: string(2) “hi”
 datatype(length)value

R.P.Vasava
• Changing/Setting a Variable’s Data Type
2 ways to change/set a variable’s datatype:

-settype( ) function:
• Syntax: settype(variable_name, datatype_name);
• Example: $x = 3.566;
settype($x, “integer”); // $x converted from float to integer
echo $x; // Output: 3
-Type Casting:
• Syntax: variable_name = (datatype_name) another_variable_name;
• Example: $x = 2.53;
$y = (int)$x;
echo $y; // Output: 2
 $x temporarily converted to integer and copied to $y

R.P.Vasava

• Ex:
<?php
$a = "123xyz";
settype($a, "integer"); // $a is now integer
echo $a;
?> o/p: 123

• Ex:
<?php
$a = 32;
echo var_dump($a) . "<br>";
?>
o/p: int(32)

R.P.Vasava
• Ex
<?php
$a = 3;
echo gettype($a) . "<br>";
?>
o/p: integer

R.P.Vasava

Casting
• If you want to change type temporary,i.e want
to use inside an expression you can use type
casting
• Syntax: (type)$variable
where type is a type of variable you wish to
cast to.
Ex: $var1=10.9;
echo (int)$var1; //$var1 is now set to 10(int)

R.P.Vasava
Operator Precedence in PHP
• Precedence of operators decides the order of execution of
operators in an expression.
• Following is the list of operators and their precedence with 1
being the highest:
Precedence Operator(s) Associativity Precedence Operator(s) Associativity
1 ** Right 10 ^ Left
2 ++ -- ~ n/a 11 | Left
3 ! n/a 12 && Left
4 * / % Left 13 || Left
5 + - . Left 14 ?: Left
6 << >> Left 15 = Right
7 < <= > >= n/a 16 and Left
8 == != n/a 17 xor Left
9 & Left R.P.Vasava 18 or Left

Unit-I
1.8 Decision-making statements:
if statement,
if-else statement,
else-if clause,
switch-case statement,
the ? operator
1.9 Loops: while loop, for loop, foreach loop
1.10 Break and continue statements
PHP Conditional Statements

if statement - executes some code only if a specified condition is


true

if...else statement - executes some code if a condition is true and


another code if the condition is false

if…..elseif....else statement - specifies a new condition to test, if


the first condition is false

switch statement - selects one of many blocks of code to be


executed

• PHP - The if Statement


• The if statement is used to execute some code only if a specified
condition is true.
• Syntax
if (condition) {
code to be executed if condition is true;
}
Example:-
<?php
$n=12;
if ($n< 20)
{
echo “$n is less than 20”;
}
?>
o/p:12 is less than 20
• PHP - The if...else Statement
Use the if....else statement to execute some
code if a condition is true and another code if
the condition is false.
• Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}


<?php
$n=12;
if ($n%2==0)
{
echo “Even number";
}
else
{
echo “Odd number";
}
?>
o/p: Even number
• PHP - The if...elseif....else Statement
Use the if....elseif...else statement to specify a new
condition to test, if the first condition is false.
• Syntax
if (condition) {
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

<?php
$marks=90;
if ($marks>=85 && $marks<=100)
{ echo "AA"; }
else if ($marks>=75 && $marks<=84)
{ echo "AB"; }
else if ($marks>=65 && $marks<=74)
{ echo "BB"; }
else if ($marks>=55 && $marks<=64)
{ echo "BC"; }
else if ($marks>=45 && $marks<=54)
{ echo "CC"; }
else if ($marks>=40 && $marks<=44)
{ echo "CD"; }
else if ($marks>=35 && $marks<=39)
{ echo "DD"; }
else
{ echo "FF"; }
?>
O/P: AA
• The PHP switch Statement
• Use the switch statement to select one of many blocks of
code to be executed.
• Syntax:-
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;

case "blue":
echo "Your favorite color is blue!";
break;

case "green":
echo "Your favorite color is green!";
break;

default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
o/p:Your favorite color is red!
• PHP Loops
In PHP, we have the following looping statements:
while - loops through a block of code as long as the
specified condition is true
do...while - loops through a block of code once, and
then repeats the loop as long as the specified
condition is true
for - loops through a block of code a specified
number of times
foreach - loops through a block of code for each
element in an array

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

<?php
$x = 1;

while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?> O/P:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

• The PHP do...while Loop


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);
<?php
$x = 1;

do
{
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
O/P:
?> The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

<?php
$x = 6;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
O/P: The number is: 6
FOR LOOP
• PHP for loops execute 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;
}
• 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

<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
O/P:-
} The number is: 0
?> The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The PHP foreach Loop
• 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;
}


<?php
//declare array
$colors = array("red", "green", "blue", "yellow");
// access array elements using foreach loop
foreach ($colors as $value)
{
echo "$value <br>";
}

?>
o/p:-red
green
blue
yellow
Print both the key and the value from the $age array:

<?php
$age = array("Peter"=>"35", “Nick"=>"37", "Joe"=>"43");

foreach($age as $x => $val)


{
echo "$x = $val <br>";
O/P:
} Peter = 35
?> Nick = 37
Joe = 43

The Break and continue Statement


• The break statement breaks the loop and
continues executing the code after the loop (if
any):
• The continue statement terminates execution
of the block of statements in a while or for
loop and continue execution of the loop with
the next iteration.
<?php
$x = 1;

while($x < 5)
{
if ($x == 3)
{
break;
}
echo "The number is: $x <br>";
$x++;
}
o/p:The number is: 1
?> The number is: 2

<?php
$x = 0;

while($x < 8)
{
if ($x == 4)
{
$x++; O/P:
continue; The number is: 0
The number is: 1
} The number is: 2
echo "The number is: $x <br>"; The number is: 3
$x++; The number is: 5
The number is: 6
} The number is: 7
?>
<?php
$stack = array('first', 'second', 'third', 'fourth', 'fifth');
foreach($stack AS $v)
{
if($v == 'second')continue;
if($v == 'fourth')break;
echo $v.'<br>';
}
?>
o/p:- first
third

Important Points
• ‘while’ and ‘for’ loops are Entry-controlled loops, but
‘do…while’ is an Exit-controlled loop.

• ‘do…while’ loop will be executed at least once (unlike


‘while’ loop), even if the condition turns out to be false in
the very first iteration.

• ‘break’ statement makes the control jumps out of the loop


or a switch statement.

• ‘continue’ statement skips the iteration further in the loop


and continues with the next iteration.
• ‘elseif’ and ‘else’ statements cannot exist without an
‘if’ statement. However, an ‘if’ statement can exist
separately.

• If a ‘break’ statement is not specified in any ‘case’ (in


‘switch…case’ statement), the control automatically
enters the next case.

• ‘foreach’ loop iterates by default for all the elements of


the array, unless the loop is broke by using ‘break’
statement.

• All the 3 parts (initialization, condition and


increment/decrement) in the ‘for’ loop are optional.
Difference between for loop & foreach loop

=>
For loop Foreach loop
1. The iteration is clearly 1. The iteration is hidden
visible.
2. The foreach loop is used
2. The for loop is used as a for arrays and
general purpose loop. collections.

3. The stop condition is 3. The stop condition has


specified easily. to be explicitly specified

1 Write a PHP program to print 1 to 10 numbers using for and while


loop statement.
2 Write a PHP code to find whether given number and string is
palindrome or not.
3 Write a PHP script to count sum of 1 to 10 using for loop.
4 Write a PHP script to find whether given number is even or odd.
5 Write a PHP script to find whether given number is prime or not
prime.
IMP QUESTIONS

6 Write a PHP code to implement a simple calculator for mathematical


operations.
7 Write a PHP script to find first 3 Armstrong number.
8 Write a PHP program to print prime numbers between ranges of 1 to
100. [A prime number is a number greater than 1 which can only be
divided by 1 and number itself.]
9 Write a PHP code to reverse a number.(without using strrev()
function)
10 Write a PHP program to print 10 to 1 numbers using while loop
statement.
11 Write a PHP program to print Fibonacci series.
12 Write a PHP script to check whether a person can vote or not based
on age [person can vote if he/she is at least 18-year-old].
13 Write a PHP script to print multiplication table for the given number.
14 Write a PHP program to check whether a number is positive, negative
or zero.
IMP QUESTIONS

(1)
<?php
// Using a for loop
echo "Numbers from 1 to 10 using for loop:";
for ($i = 1; $i <= 10; $i++)
{
echo $i . " ";
}
echo "<br>";

// Using a while loop


echo "Numbers from 1 to 10 using while loop:";
$i = 1; // Initialize the counter
while ($i <= 10) {
echo $i . " ";
$i++; // Increment the counter
}
?>
(2)
<?php
function isPalindrome($input)
{
$str = (string) $input; // Convert input to a string and reverse it
$reversed = strrev($str);
return $str === $reversed; // Compare the original and reversed strings
}
$number = 121; // Example number
$string = "madam"; // Example string
if (isPalindrome($number)) // Check if the number is a palindrome using if-else
{ echo "The number $number is a palindrome". "<br>"; }
else
{ echo "The number $number is not a palindrome". "<br>"; }
if (isPalindrome($string)) // Check if the string is a palindrome using if-else
{ echo "The string '$string' is a palindrome"."<br>";}
else
{ echo "The string '$string' is not a palindrome"."<br>"; }
?>

(3)
<?php
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i; // Add the current number to the sum
}
echo "The sum of numbers from 1 to 10 is: $sum";
?>
(4)
<?php
$number = 7;
if ($number % 2 == 0)
{
echo "The number $number is even";
} else
{
echo "The number $number is odd";
}
?>

(5)
<?php
$number = 15;
function isPrime($num) // Function to check if the number is prime
{
if ($num <= 1)
{
return false; // 0 and 1 are not prime numbers
}
for ($i = 2; $i <= sqrt($num); $i++) // Check for factors from 2 to the square root of the number
{ if ($num % $i == 0)
{ return false; // Number is divisible by $i, so it's not prime
}
} return true; // If no factors were found, it's a prime number
}
// Check if the number is prime
if (isPrime($number))
{ echo "The number $number is prime"; }
else
{ echo "The number $number is not prime"; }
?>
(6)
<?php
$num1 = 10;
$num2 = 5;
$operation = 'add'; // Change to 'subtract', 'multiply', or 'divide' to test other operations
echo "The result of $operation $num1 and $num2 is: ";
if ($operation == 'add')
{ echo $num1 + $num2;
} elseif ($operation == 'subtract')
{ echo $num1 - $num2;
} elseif ($operation == 'multiply')
{ echo $num1 * $num2;
} elseif ($operation == 'divide')
{
if ($num2 != 0)
{ echo $num1 / $num2; }
else
{ echo "Error: Division by zero is not allowed!"; }
} else { echo "Invalid operation!";}
?>

(7)
(7) // Check if the sum of the digits raised to the
<?php power of 'digits' equals the original number
// Function to check if a number is Armstrong return $sum == $num;
function isArmstrong($num) }
{
// Find the number of digits in the number // Input: Number to check
$digits = strlen((string)$num); $number = 153; // You can change this number
$sum = 0; // Initialize sum to 0 to test others
$temp = $num; // Store the original number in
temp // Check if the number is Armstrong
// Loop to calculate the sum of digits raised to the if (isArmstrong($number)) {
power of the number of digits echo "$number is an Armstrong number";
while ($temp > 0) } else {
{ echo "$number is not an Armstrong number";
// Get the last digit of the number }
$digit = $temp % 10; ?>
// Add the digit raised to the power of 'digits'
$sum += pow($digit, $digits);
// Remove the last digit from the number
$temp = (int)($temp / 10);
}

(8)
<?php
// Function to check if a number is prime
function isPrime($num)
{
// Check if the number is less than or equal to 1 (not prime)
if ($num <= 1)
{
return false;
}
// Check for factors from 2 to the square root of the number
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false; // The number is divisible by $i, so it's not prime
}
}
return true; // If no factors were found, it's a prime number
}
echo "Prime numbers between 1 and 100 are:\n";
for ($num = 1; $num <= 100; $num++) {
if (isPrime($num)) {
echo $num . "\n"; // Print the prime number
}
}
?>
(9)

<?php
function reverseNumber($num) // Function to reverse a number
{
$reversed = 0;
// Loop until the number becomes 0
while ($num > 0) {
// Extract the last digit of the number
$digit = $num % 10;

// Add the digit to the reversed number and shift the digits
$reversed = ($reversed * 10) + $digit;
// Remove the last digit from the original number
$num = (int)($num / 10);
}
return $reversed;
}
$number = 123; // Change this number to test with others
echo "The reversed number of $number is: " . reverseNumber($number) . "\n";
?>
(10)
<?php
$num = 10;
while ($num >= 1)
{
echo $num . "\n";
$num--;
}
?>

(11)
<?php
// Number of terms you want in the Fibonacci series
$terms = 10;
// Initialize the first two numbers of the Fibonacci sequence
$a = 0;
$b = 1;
echo "Fibonacci Series up to $terms terms: <br>";

// Print the Fibonacci numbers up to the nth term


for ($i = 0; $i < $terms; $i++)
{
echo $a . " "; //prints the current term ($a) followed by a space.

// Update the values of $a and $b for the next term


$nextTerm = $a + $b; //calculates the next term in the sequence by summing the
previous two terms.
$a = $b;
$b = $nextTerm;
}
?>
(12)
<?php
$personAge = 20;
if ($personAge >= 18)
{
echo "Age: $personAge"."<br>";
echo "You are eligible to vote.";
} else
{
echo "Age: $personAge"."<br>";
echo "You are not eligible to vote.";
}
?>

(13)
<?php
$number = 5; // You can change this to any number
// Loop to display the multiplication table
echo "Multiplication Table for $number:<br>";
for ($i = 1; $i <= 10; $i++)
{
echo "$number x $i = " . ($number * $i) . "<br>";
}
?>
(14) <?php
$number = -5; // Replace this value with the number you want to check
// Check if the number is positive, negative, or zero
if ($number > 0)
{
echo "The number $number is positive.";
} elseif ($number < 0)
{
echo "The number $number is negative.";
} else {
echo "The number is zero.";
}
?>

You might also like