Attachment
Attachment
PHP
Day 1.1 and 1.2:
History:
Common Use:
Development Tools:
Example:
<?php
echo 'Hello World';
?>
<?php
$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:
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
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!";
?>
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>";
?>
4. print_r() Function
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>";
?>
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:
● Variable Scope
● PHP $ and $$ Variables
<?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.
<?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.
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:
● Data Types
● Type Juggling
$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);
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.
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);
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.
$x = "Hello world!";
$x = null;
var_dump($x);
Type Juggling
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.
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:
● 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.
$var = (type)expr;
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:
Syntax
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.
Multiplicatio
* $x * $y Product of the operands
n
Exponentiati
** $x ** $y $x raised to the power $y
on
<?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";
?>
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.
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.
<?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);
?>
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';
?>
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.
<?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.
Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used
to increment or decrement values.
++ Post-Increment $x++
First returns $x, then increment
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
<?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 ==
$x <=> $y Identical to 0 (both are equal)
$y
<?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:
Operators
10.Bitwise Operators
Bitwise Operators
& And $x & $y Bits that are set in both $x and $y 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.#
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:
Example:
$first = 5;
$second = 3;
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;
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;
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;
Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)
Example:
$first = 5;
$second = 1;
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )
Example:
$first = 5;
$second = 1;
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:
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
** exponentiation
++ -- increment/decrement
instanceof types
! logical
*/ multiplication/division
% modulo
^ bitwise XOR
| bitwise OR
|| logical or
?? null coalescing
?: ternary
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.
Syntax
define( 'CONSTANT_NAME', value, case_insensitive )
<?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;
?>
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";
}
?>
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:
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
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.
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:
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:
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 . " ";
}
?>
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++;
}
?>
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);
?>
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";
}
?>