0% found this document useful (0 votes)
17 views61 pages

Attachment

Web-based application development with PHP involves creating dynamic websites using PHP, a server-side scripting language known for its ease of use and flexibility. The document covers PHP's history, features, common uses, development tools, advantages, and various programming concepts including expressions, control statements, variable scope, data types, and type casting. It also provides examples and explanations of PHP syntax and functionality.

Uploaded by

waghkaveri5
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)
17 views61 pages

Attachment

Web-based application development with PHP involves creating dynamic websites using PHP, a server-side scripting language known for its ease of use and flexibility. The document covers PHP's history, features, common uses, development tools, advantages, and various programming concepts including expressions, control statements, variable scope, data types, and type casting. It also provides examples and explanations of PHP syntax and functionality.

Uploaded by

waghkaveri5
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/ 61

Web Based Application Development with

PHP
Day 1.1 and 1.2:

PHP Means Pretty Hard to Process Just Joking 😀


PHP is a recursive acronym that stands for "Hypertext Preprocessor". It was
originally an abbreviation for "Personal Home Page".

What is web based application development with PHP ?

Web-based application development with PHP involves creating dynamic websites


and web applications using PHP, a server-side scripting language. PHP is widely used
for developing scalable, robust, and efficient web applications due to its ease of use,
flexibility, and compatibility with various databases and web servers.

Features of Web-based Application Development with PHP:


●​ Open Source
●​ Platform Independent
●​ Simple and Easy
●​ Database
●​ Fast
●​ Maintenance
●​ Fast Performance
●​ Vast Community Support
●​ Server-side Scripting Language
●​ Integration with Databases
●​ Cross-platform Compatibility or platform independent
●​ Security
●​ Dynamic Content Generation

History:

●​ 1994: Rasmus Lerdorf, a Danish-Canadian programmer, conceived of PHP


while using early versions on his homepage to track visitors. The first version
was called Personal Home Page Tools (PHP Tools) and was written in C.
●​ 1995: Lerdorf released the source code for PHP Tools to the public, allowing
developers to use it and contribute to its improvement.
●​ 1995: Lerdorf rewrote PHP Tools and renamed it PHP/FI (Personal Home
Page/Forms Interpreter). PHP/FI included mSQL support and a parser engine
that could understand special macros and common home page utilities.
●​ 1996: PHP/FI was in use on at least 15,000 websites worldwide.
●​ 1997: PHP/FI was in use on over 50,000 websites worldwide. The development
of PHP became more organized and was no longer just Lerdorf's project.
●​ 2004: PHP 5 was released with the updated Zend Engine 2.0.

Common Use:

●​ E-commerce platforms (e.g., Magento, OpenCart, CI, Laravel, Zend)


●​ Content Management Systems (e.g., WordPress, Joomla)
●​ Customer Relationship Management (CRM) systems
●​ Social networking platforms
●​ RESTful APIs for web and mobile applications

Development Tools:

●​ IDEs like PhpStorm, Visual Studio Code, or Sublime Text.


●​ Local development environments like XAMPP, MAMP, or Docker.
Advantages of PHP:

●​ Open-source and cost-effective.


●​ Extensive community support.
●​ Regular updates and improvements.
●​ Extensive libraries and frameworks for rapid development.

Setup Xampp Server

Example:

<?php ​

echo 'Hello World';

?>

<?php

echo 'Hello Guys';

$i = 10;
if($i >= 8)
{
echo '10 is greater than 8';
}else
{
echo '8 is greater than 10';
}

?>

<h1>Hello World</h1>
<h2>Hello World</h2>
Web Based Application Development with
PHP
Day 1.3:

Chapter 1: Expressions and Control Statements in PHP

●​ Run PHP with HTML content


●​ PHP Comments
●​ Echo and Print
●​ Print_r() functions
●​ Variables
●​ Loosely Typed language

1. Run PHP with HTML Content

PHP can be embedded directly into HTML, allowing dynamic content generation.

Example

<!DOCTYPE html>​
<html>​
<head>​
<title>PHP with HTML</title>​
</head>​
<body>​
<h1>Welcome to PHP with HTML</h1>​
<?php​
echo "<p>This content is generated using PHP!</p>";​
$year = date("Y");​
echo "<footer>Current Year: $year</footer>";​
?>​
</body>​
</html>

2. PHP Comments

PHP supports single-line and multi-line comments.

Example

<?php​
// This is a single-line comment​

# This is also a single-line comment​

/*​
This is a multi-line comment​
explaining the code below.​
*/​

echo "PHP comments are easy to use!";​
?>

3. Echo and Print

Both echo and print are used to output data in PHP. echo is slightly faster and can take
multiple parameters, whereas print returns a value.

Example

<?php​
// Using echo​
echo "Hello, World!<br>";​
echo "PHP", " is", " awesome!<br>";​

// Using print​
print "Learning PHP is fun!<br>";​
?>

S.No. echo statement print statement

echo accepts a list of arguments


The print accepts only one
1. (multiple arguments can be
argument at a time.
passed), separated by commas.

2. It does not return any value. It returns the value 1.

It displays the outputs of one or


The print outputs only the
3. more strings separated by
strings.
commas.

It is comparatively faster than It is slower than an echo


4. the print statement. statement.

4. print_r() Function

The print_r() function is used to print human-readable information about arrays or


objects.
Example
<?php​
$array = array("Apple", "Banana", "Cherry");​

// Using print_r to display the array​
echo "<pre>";​
print_r($array);​
echo "</pre>";​
?>​

5. Variables

Variables in PHP start with a $ symbol and can store various types of data.

Example
<?php​
$name = "John"; // String​
$age = 25; // Integer​
$price = 19.99; // Float​
$isAvailable = true; // Boolean​

echo "Name: $name<br>";​
echo "Age: $age<br>";​
echo "Price: $price<br>";​
echo "Available: " . ($isAvailable ? "Yes" : "No") . "<br>";​
?>

6. Loosely Typed Language

PHP is a loosely typed language, meaning you don’t need to define the variable type
explicitly.

Example
<?php​
$variable = "Hello"; // String​
echo "String: $variable<br>";​

$variable = 123; // Integer​
echo "Integer: $variable<br>";​

$variable = true; // Boolean​
echo "Boolean: " . ($variable ? "True" : "False") . "<br>";​
?>
Web Based Application Development with
PHP
Day 1.4:

Chapter 1: Expressions and Control Statements in PHP

●​ Variable Scope
●​ PHP $ and $$ Variables

1.​ Variable Scope


Local Variable
The variables that are declared within a function are called local variables
for that function. These local variables have their scope only in that
particular function in which they are declared. This means that these
variables cannot be accessed outside the function, as they have local
scope.

A variable declaration outside the function with the same name is


completely different from the variable declared inside the function. Let's
understand the local variables with the help of an example:

<?php ​
function local_var() ​
{ ​
$num = 45; //local variable ​
echo "Local variable declared inside the function is: ".
$num; ​
} ​
local_var(); ​
?>
Global Variable
The global variables are the variables that are declared outside the
function. These variables can be accessed anywhere in the program. To
access the global variable within a function, use the GLOBAL keyword
before the variable. However, these variables can be directly accessed or
used outside the function without any keyword. Therefore there is no need
to use any keyword to access a global variable outside the function.

Let's understand the global variables with the help of an example:

<?php ​
$name = "Sanaya Sharma"; //Global Variable ​
function global_var() ​
{ ​
global $name; ​
echo "Variable inside the function: ". $name; ​
echo "</br>"; ​
} ​
global_var(); ​
echo "Variable outside the function: ". $name; ​
?>

Another example:

<?php
$name = "Sanaya Sharma"; //global variable
function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>

Static Variables
In PHP, the static keyword is used to declare variables that retain their value
between function calls. Unlike regular variables, which are reinitialized each time
a function is called, static variables preserve their value even after the function
execution is complete.

Syntax​
static $variableName = initialValue;

​ Example

function counter() {​
static $count = 0; // Static variable​
$count++; // Increment the count​
echo "Count: $count\n";​
}​

counter(); // Output: Count: 1​
counter(); // Output: Count: 2​
counter(); // Output: Count: 3​

The $count variable is initialized only once when the function is first called.
Its value is preserved across subsequent calls to the counter() function.

2.​ PHP $ and $$ Variables


The $x (single dollar) is the normal variable with the name x that stores any value
like string, integer, float, etc.

The $$x (double dollar) is a reference variable that stores the value which can be
accessed by using the $ symbol before the $x value. These are called variable
variables in PHP.

Variable Variables:- Variable variables are simply variables whose names are
dynamically created by another variable’s value.
●​ $x stores the value “Geeks” of String type.
●​ Now the reference variable $$x stores the value “for Geeks” in it of String
type.
​ Example:

<?php ​

// Declare variable and initialize it​
$x = "Geeks";​ ​

// Reference variable​
$$x = "GeeksforGeeks";​

// Display value of x​
echo $x . "\n"; ​

// Display value of $$x ($Geeks)​
echo $$x . "\n"; ​

// Display value of $Geeks​
echo "$Geeks";​

?>​
Web Based Application Development with
PHP
Day 1.5:

Chapter 1: Expressions and Control Statements in PHP

●​ Data Types
●​ Type Juggling

1.​ Data Types


Variables can store data of different types, and different data types can do
different things.

PHP supports the following data types:


1.​ String
2.​ Integer
3.​ Float (floating point numbers - also called double)
4.​ Boolean
5.​ Array
6.​ Object
7.​ NULL

Getting the Data Type


You can get the data type of any object by using the var_dump() function.
Example:
The var_dump() function returns the data type and the value:

$x = 5;​
var_dump($x);
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:

$x = "Hello world!";​
$y = 'Hello world!';​

var_dump($x);​
echo "<br>";​
var_dump($y);

​ PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
●​ An integer must have at least one digit
●​ An integer must not have a decimal point
●​ An integer can be either positive or negative
●​ Integers can be specified in: decimal (base 10), hexadecimal (base 16),
octal (base 8), or binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns
the data type and value:

$x = 5985;​
var_dump($x);

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:

$x = 10.365;​
var_dump($x);

​ PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

$x = true;​
var_dump($x);

​ Booleans are often used in conditional testing.

​ 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:

$cars = array("Volvo","BMW","Toyota");​
var_dump($cars);


​ 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 that can have properties like model,
color, etc. We can define variables like $model, $color, and so on, to hold the
values of these properties.

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

If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.

class Car {​
public $color;​
public $model;​
public function __construct($color, $model) {​
$this->color = $color;​
$this->model = $model;​
}​
public function message() {​
return "My car is a " . $this->color . " " . $this->model . "!";​
}​
}​

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

PHP NULL Value


Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of
NULL.

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

$x = "Hello world!";​
$x = null;​
var_dump($x);

Type Juggling

PHP is known as a dynamically typed language. The type of a variable in PHP


changes dynamically. This feature is called "type juggling" in PHP.

In C, C++ and Java, you need to declare the variable and its type before using
it in the subsequent code. The variable can take a value that matches with the
declared type only.

Explicit type declaration of a variable is neither needed nor supported in PHP.


Hence the type of PHP variable is decided by the value assigned to it, and not
the other way around. Further, when a variable is assigned a value of different
type, its type too changes.

Example:

<?php​
$var = "Hello";​
echo "The variable \$var is of " . gettype($var) . " type"
.PHP_EOL;​

$var = 10;​
echo "The variable \$var is of " . gettype($var) . " type"
.PHP_EOL;​

$var = true;​
echo "The variable \$var is of " . gettype($var) . " type"
.PHP_EOL;​

$var = [1,2,3,4];​
echo "The variable \$var is of " . gettype($var) . " type"
.PHP_EOL;​
?>
Web Based Application Development with
PHP
Day 1.6:

Chapter 1: Expressions and Control Statements in PHP

●​ Type Casting
●​ Expressions & Operators

Type Casting
The term "Type Casting" refers to conversion of one type of data to another. Since PHP
is a weakly typed language, the parser coerces certain data types into others while
performing certain operations. For example, a string having digits is converted to integer
if it is one of the operands involved in the addition operation.

Type Casting Operators


To convert an expression of one type to another, you need to put the data type of the
latter in parenthesis before the expression.

$var = (type)expr;

Some of the type casting operators in PHP are −

(int) or (integer) casts to an integer

(bool) or (boolean) casts to a boolean

(float) or (double) or (real) casts to a float

(string) casts to a string

(array) casts to an array


(object) casts to an object

Examples:

<?php​
$a = 9.99;​
$b = (int)$a;​
var_dump($b);​
?>​

<?php​
$a = "99";​
$b = (int)$a;​
var_dump($b);​
?>​

<?php​
$a = "10 Rs.";​
$b = (int)$a;​
var_dump($b);​

$a = "$100";​
$b = (int)$a;​
var_dump($b);​
?>

<?php
$a = "100";
$b = (double)$a;
var_dump($b);

$a = "9.99";
$b = (float)$a;
var_dump($b);
?>
<?php
$a = 100;
$b = (string)$a;
var_dump($b);

$x = 55.50;
$y = (string)$x;
var_dump($y);
?>

<?php
$a = 100;
$b = (bool)$a;

$x = 0;
$y = (bool)$x;

$m = "Hello";
$n = (bool)$m;

var_dump($b);
var_dump($y);
var_dump($n);
?>

Expressions & Operators

Expressions:

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 expression
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression

Operators:

1.​ Arithmetic Operators


2.​ Logical or Relational Operators
3.​ Comparison Operators
4.​ Conditional or Ternary Operators
5.​ Assignment Operators
6.​ Spaceship Operators (Introduced in PHP 7)
7.​ Array Operators
8.​ Increment/Decrement Operators
9.​ String Operators
10.​Bitwise 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


– Subtraction $x – $y Differences the operands

Multiplicatio
* $x * $y Product of the operands
n

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

Exponentiati
** $x ** $y $x raised to the power $y
on

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

<?php​
// Define two numbers​
$x = 10;​
$y = 3;​

// Addition​
echo "Addition: " . ($x + $y) . "\n";​

// Subtraction​
echo "Subtraction: " . ($x - $y) . "\n";​

// Multiplication​
echo "Multiplication: " . ($x * $y) . "\n";​

// Division​
echo "Division: " . ($x / $y) . "\n";​

// Exponentiation​
echo "Exponentiation: " . ($x ** $y) . "\n";​

// Modulus​
echo "Modulus: " . ($x % $y) . "\n";​
?>

Logical 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 True if both the operands are true


and $x and $y
AND else false

Logical True if either of the operands is


or $x or $y
OR true else false
Logical True if either of the operands is
xor $x xor $y
XOR true and false if both are true

Logical True if both the operands are true


&& $x && $y
AND else false

Logical True if either of the operands is


|| $x || $y
OR true else false

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

<?php​
$x = 50;​
$y = 30;​
if ($x == 50 and $y == 30)​
echo "and Success \n";​

if ($x == 50 or $y == 20)​
echo "or Success \n";​

if ($x == 50 xor $y == 20)​
echo "xor Success \n";​

if ($x == 50 && $y == 30)​
echo "&& Success \n";​

if ($x == 50 || $y == 20)​
echo "|| Success \n";​

if (!$z)​
echo "! Success \n";​
?>

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


== Equal To $x == $y
are equal

Returns True if both the operands


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

Returns True if both the operands


<> Not Equal To $x <> $y
are unequal
Returns True if both the operands
=== Identical $x === $y are equal and are of the same
type

Returns True if both the operands


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

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

Returns True if $x is greater than


> Greater Than $x > $y
$y

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


<= $x <= $y
Equal To equal to $y

Greater Than Returns True if $x is greater than


>= $x >= $y
or Equal To or equal to $y

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

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

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;

Here, the condition will either evaluate as true or false. If the condition evaluates to
True, then value1 will be assigned to the variable $var otherwise value2 will be assigned
to it.

<?php​
$x = -12;​
echo ($x > 0) ? 'The number is positive' : 'The number is
negative';​
?>

Operator Name Operation

If the condition is true? then $x : or else $y. This


means that if the condition is true then the left
?: Ternary
result of the colon is accepted otherwise the
result is on right.
Web Based Application Development with
PHP
Day 1.7:

Chapter 1: Expressions and Control Statements in PHP

●​ Expressions & Operators

Operators
5.​ Assignment Operators
6.​ Spaceship Operators (Introduced in PHP 7)
7.​ Array Operators
8.​ Increment/Decrement Operators
9.​ String Operators
10.​Bitwise Operators

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


= Assign $x = $y
value of the operand on the right
Simple Addition same as $x = $x +
+= Add then Assign $x += $y
$y

Subtract then Simple subtraction same as $x =


-= $x -= $y
Assign $x – $y

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


*= $x *= $y
Assign $y

Divide then Simple division same as $x = $x /


/= $x /= $y
Assign (quotient) $y

Divide then Simple division same as $x = $x %


%= Assign $x %= $y
$y
(remainder)

<?php​
// Simple assign operator​
$y = 75;​
echo $y, "\n";​

// Add then assign operator​
$y = 100;​
$y += 200;​
echo $y, "\n";​

// Subtract then assign operator​
$y = 70;​
$y -= 10;​
echo $y, "\n";​

// Multiply then assign operator​
$y = 30;​
$y *= 20;​
echo $y, "\n";​

// Divide then assign(quotient) operator​
$y = 100;​
$y /= 5;​
echo $y, "\n";​

// Divide then assign(remainder) operator​
$y = 50;​
$y %= 5;​
echo $y;​
?>

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

Returns true if both has same


== Equality $x == $y
key-value pair

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

Returns True if both have the same


=== Identity $x === $y key-value pair in the same order and
of the same type

Non-Ident Returns True if both are not identical


!== $x !== $y
ity to each other

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


<?php​
$x = array("k" => "Car", "l" => "Bike");​
$y = array("a" => "Train", "b" => "Plane");​

var_dump($x + $y);​
var_dump($x == $y) + "\n";​
var_dump($x != $y) + "\n";​
var_dump($x <> $y) + "\n";​
var_dump($x === $y) + "\n";​
var_dump($x !== $y) + "\n";​
?>

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

First increments $x by one, then


++ Pre-Increment ++$x
return $x

First decrements $x by one, then


— Pre-Decrement –$x
return $x

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

First returns $x, then decrement


— Post-Decrement $x—
it by one

<?php​
$x = 2;​
echo ++$x, " First increments then prints \n";​
echo $x, "\n";​

$x = 2;​
echo $x++, " First prints then increments \n";​
echo $x, "\n";​

$x = 2;​
echo --$x, " First decrements then prints \n";​
echo $x, "\n";​

$x = 2;​
echo $x--, " First prints then decrements \n";​
echo $x;​
?>

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


.= $x.=$y
assignment assigns, same as $x = $x.$y

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

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:
Operator Syntax Operation

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

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

$x <= Identical to -1 (right is greater) or identical


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

$x >= Identical to 1 (if left is greater) or identical


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

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

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

<?php​
$x = 50;​
$y = 50;​
$z = 25;​

echo $x <=> $y;​
echo "\n";​

echo $x <=> $z;​
echo "\n";​

echo $z <=> $y;​
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;​
?>
Web Based Application Development with
PHP
Day 1.8:

Chapter 1: Expressions and Control Statements in PHP

●​ Expressions & Operators

Operators
10.​Bitwise Operators

Bitwise Operators

Operator Name Example Result

& And $x & $y Bits that are set in both $x and $y are set.

| Or $x | $y Bits that are set in either $x or $y are set.

^ Xor $x ^ $y Bits that are set in $x or $y but not both are


set.

~ Not ~$x Bits that are set in $x are not set, and vice
versa.
<< Shift left $x << $y Shift the bits of $x $y steps to the left.#

>> Shift $x >> $y Shift the bits of $x $y steps to the right.*


right

# Each step means 'multiply by two'​


* Each step means 'divide by two'

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. The mathematical operations such as addition , subtraction , multiplication
etc. can be performed at bit-level for faster processing. In PHP, the operators that works
at bit level are:

& (Bitwise AND) :


This is a binary operator i.e. it works on two operand. 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.

Example:

$first = 5;
$second = 3;

echo $first & $second;

Output: The bitwise & of both these value will be 1.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)

| (Bitwise OR) :
This is also binary operator i.e. works on two operand. 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.

Example:

$first = 5;
$second = 3;

echo $first | $second;

Output: The bitwise | of both these value will be 7.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)

^ (Bitwise XOR ) :
This is also binary operator i.e. works on two operand. This is also known as Exclusive
OR operator. Bitwise XOR takes two numbers as operands and does XOR on every bit
of two numbers. The result of XOR is 1 if the two bits are different.

Example:

$first = 5;
$second = 3;

echo $first ^ $second;

Output: The bitwise ^ of both these value will be 6.

Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)

~ (Bitwise NOT) :
This is a unary operator i.e. works on only one operand. Bitwise NOT operator takes
one number and inverts all bits of it.

Example:

$first = 5;

echo ~$first;

Output: The bitwise '~' of this number will be -6.

Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)

<< (Bitwise Left Shift) :


This is a binary operator i.e. works on two operand. 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.

Example:

$first = 5;
$second = 1;

echo $first << $second;

Output: The bitwise << of both these value will be 10.

Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )

>> (Bitwise Right Shift) :


This is also binary operator i.e. works on two operand. 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.

Example:

$first = 5;
$second = 1;

echo $first >> $second;

Output: The bitwise >> of both these value will be 2.

Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
Web Based Application Development with
PHP
Day 1.9:

Chapter 1: Expressions and Control Statements in PHP

PHP Operator Precedence(Priority)

Precedence of operators decides the order of execution of operators in an expression.


For example in 2+6/3, division of 6/3 is done first and then addition of 2+2 takesplace
because division operator / has higher precedence over addition operator +. To force a
certain operator to be called before other, parentheses should be used. In this example,
(2+6)/3 performs addition first, followed by division.

Some operators may have same level of precedence. In that case, the order of
associativity (either left or right) decides the order of operations. Operators of same
precedence level but are non-associative cannot be used next to each other. Following
table lists PHP operators with decreasing order of precedence

Operators purpose

clone new clone and new

** exponentiation

++ -- increment/decrement

~(int) (float) (string) (array) (object) casting


(bool)

instanceof types

! logical

*/ multiplication/division
% modulo

+-. arithmetic and string

<< >> bitwise shift

< <= > >= comparison

== != === !== <> <=> comparison

& bitwise and/references

^ bitwise XOR

| bitwise OR

&& logical and

|| logical or

?? null coalescing

?: ternary

= += -= *= **= /= .= %= &= |= ^= assignment operators


<<= >>= ??=

yield from yield from

yield yield

print print

and logical

xor logical

or logical

PHP Constants

Constants in PHP are identifiers or names that can be assigned any fixed values and
cannot change during the execution of a program. They remain constant throughout the
program and cannot be changed during the execution. Once a constant is defined, it
cannot be undefined or redefined.

By convention, constant identifiers are always written in upper case. By default, a


constant is always case-sensitive. 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.

Creating a Constant using define() Function

The define() function in PHP is used to create a constant as shown below:

Syntax​

define( 'CONSTANT_NAME', value, case_insensitive )

The parameters are as follows:

name: The name of the constant.


value: The value to be stored in the constant.
case_insensitive: Defines whether a constant is case insensitive. By default this value is
False, i.e., case sensitive.

<?php​

// This creates a case-sensitive constant​
define("WELCOME", "PHP Programming");​
echo WELCOME . "\n";​

// This creates a case-insensitive constant​
define("HELLO", "PHP Programming", true);​
echo hello;​

?>

Decision making control statements:

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

if Statement: This statement allows us to set a condition. On being TRUE, the following
block of code enclosed within the if clause will be executed.

Syntax :​

if (condition){​
// if TRUE then execute this code​
}

Example:

<?php ​
$x = 12; ​

if ($x > 0) { ​
​ echo "The number is positive"; ​
} ​
?> ​
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the
block of code within if will be executed. But what if the condition is not TRUE and we
want to perform an action? This is where else comes into play. If a condition is TRUE
then if block gets executed, otherwise else block gets executed.

Syntax:​

if (condition) {​
// if TRUE then execute this code​
}​
else{​
// if FALSE then execute this code​
}
Example:
<?php ​
$x = -12; ​

if ($x > 0) { ​
echo "The number is positive"; ​
} ​

else{ ​
echo "The number is negative"; ​
} ​
?>

if…elseif…else Statement: This allows us to use multiple if…else statements. We use


this when there are multiple conditions of TRUE cases.

Syntax:​
if (condition) {​
// if TRUE then execute this code​
}​
elseif() {​
// if TRUE then execute this code​
}​
elseif () {​
// if TRUE then execute this code​
}​
else {​
// if FALSE then execute this code​
}

<?php ​
$x = "August"; ​

if ($x == "January") { ​
​ echo "Happy Republic Day"; ​
} ​

elseif ($x == "August") { ​
​ echo "Happy Independence Day!!!"; ​
} ​

else{ ​
​ echo "Nothing to show"; ​
} ​
?> ​
switch Statement: The “switch” performs in various cases i.e., it has various cases to
which it matches the condition and appropriately executes a particular case block. It first
evaluates an expression and then compares with the values of each case. If a case
matches then the same case is executed. To use switch, we need to get familiar with
two different keywords namely, break and default.

●​ The break statement is used to stop the automatic control flow into the next
cases and exit from the switch case.
●​ The default statement contains the code that would execute if none of the cases
match.

Syntax:​

switch(n) {​
case statement1:​
code to be executed if n==statement1;​
break;​
case statement2:​
code to be executed if n==statement2;​
break;​
case statement3:​
code to be executed if n==statement3;​
break;​
case statement4:​
code to be executed if n==statement4;​
break;​
......​
default:​
code to be executed if n != any case;

Example:

<?php ​
$n = "February"; ​

switch($n) { ​
​ case "January": ​
​ ​ echo "Its January"; ​
​ ​ break; ​
​ case "February": ​
​ ​ echo "Its February"; ​
​ ​ break; ​
​ case "March": ​
​ ​ echo "Its March"; ​
​ ​ break; ​
​ case "April": ​
​ ​ echo "Its April"; ​
​ ​ break; ​
​ case "May": ​
​ ​ echo "Its May"; ​
​ ​ break; ​
​ case "June": ​
​ ​ echo "Its June"; ​
​ ​ break; ​
​ case "July": ​
​ ​ echo "Its July"; ​
​ ​ break; ​
​ case "August": ​
​ ​ echo "Its August"; ​
​ ​ break; ​
​ case "September": ​
​ ​ echo "Its September"; ​
​ ​ break; ​
​ case "October": ​
​ ​ echo "Its October"; ​
​ ​ break; ​
​ case "November": ​
​ ​ echo "Its November"; ​
​ ​ break; ​
​ case "December": ​
​ ​ echo "Its December"; ​
​ ​ break; ​
​ default: ​
​ ​ echo "Doesn't exist"; ​
} ​
?> ​
Web Based Application Development with
PHP
Day 1.10:

Chapter 1: Expressions and Control Statements in PHP

break and continue statement in PHP

The break and continue both are used to skip the iteration of a loop. These keywords
are helpful in controlling the flow of the program. Difference between break and
continue:

●​ The break statement terminates the whole iteration of a loop whereas continue
skips the current iteration.
●​ The break statement terminates the whole loop early whereas the continue
brings the next iteration early.
●​ In a loop for switch, break acts as terminator for case only whereas continue 2
acts as terminator for case and skips the current iteration of loop.

Example:

<?php​
for ($i = 1; $i < 10; $i++) {​
​ if ($i % 2 == 0) {​
​ ​ continue;​
​ }​
​ echo $i . " ";​
}​
?>​

Example:

<?php​
for ($i = 1; $i < 10; $i++) {​
​ if ($i == 5) {​
​ ​ break;​
​ }​
​ echo $i . " ";​
}​
?>​

Break Continue

1 The break statement is used The continue statement is used to


. to jump out of a loop. skip an iteration from a loop

Its syntax is -: Its syntax is -:


2
.
break; continue;

3 The break is a keyword continue is a keyword present in the


. present in the language language

4 It can be used with loops It can be used with loops ex-: for
. ex-: for loop, while loop. loop, while loop.
5 The break statement is also We can use continue with a switch
. used in switch statements statement to skip a case.

PHP Loops

Like other programming languages, PHP Loops are used to repeat a block of code
multiple times based on a given condition. PHP provides several types of loops to
handle different scenarios, including while loops, for loops, do…while loops, and
foreach loops. In this article, we will explore the different types of loops in PHP, their
syntax, and examples.

Why Use Loops?

Loops allow you to execute a block of code multiple times without rewrite the code. This
is useful when working with repetitive tasks, such as:

●​ Iterating through arrays or data structures


●​ Performing an action a specific number of times
●​ Waiting for a condition to be met before proceeding

1.​ PHP for Loop


2.​ PHP while Loop
3.​ PHP do-while Loop
4.​ PHP foreach Loop

PHP for Loop

PHP for loop is used when you know exactly how many times you want to iterate
through a block of code. It consists of three expressions:

●​ Initialization: Sets the initial value of the loop variable.


●​ Condition: Checks if the loop should continue.
●​ Increment/Decrement: Changes the loop variable after each iteration.

Syntax​

for ( Initialization; Condition; Increment/Decrement ) {​
// Code to be executed​
}

<?php ​

// Code to illustrate for loop​
for ($num = 1; $num <= 5; $num += 1) {​
echo $num . " ";​
} ​

?>

PHP while Loop

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

Syntax​

while ( condition ) {​
// Code is executed​
}

<?php​

$num = 1;​

while ($num <= 5) {​
echo $num . " ";​
$num++;​
}​

?>

PHP do-while Loop

The do-while loop is an exit control loop which means, it first enters the loop, executes
the statements, and then checks the condition. Therefore, a statement is executed at
least once using the do…while loop. After executing once, the program is executed as
long as the condition holds true.
Syntax​

do {​
// Code is executed​
} while ( condition );

<?php​

$num = 1;​

do {​
echo $num . " ";​
$num++;​
} while ($num <= 5);​

?>

PHP foreach Loop

This foreach loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.

Syntax:​

foreach ( $array as $value ) {​
// Code to be executed​
}​

// or​

foreach ( $array as $key => $value ) {​
// Code to be executed​
}

<?php​

// foreach loop over an array ​
$arr = array (10, 20, 30, 40, 50, 60);​

foreach ($arr as $val) { ​
echo $val . " ";​
}​

echo "\n";​

// foreach loop over an array with keys​
$ages = array(​
"John" => 25, ​
"Alice" => 30, ​
"Bob" => 22​
);​

foreach ($ages as $name => $age) { ​
echo $name . " => " . $age . "\n";​
}​

?>

You might also like