WK 10 PHP Part II
WK 10 PHP Part II
PHP
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 1 / 24
Operator Operator
Operator
b An operator is a special symbol or keyword used to perform an operation on one or more operands
and return a result
b An operand is what operators are applied to. For example, 5 times 2 contains two operands, 5 and 2
and one ’×’ operator
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 2 / 24
Operator Operator
Operator
b An operator is a special symbol or keyword used to perform an operation on one or more operands
and return a result
b An operand is what operators are applied to. For example, 5 times 2 contains two operands, 5 and 2
and one ’×’ operator
b Based on number of operands, PHP operators can be classified into three classes, like other similar
languages
Unary Operator
b Increment (++): Adds 1 to its operand. $abc = 123; var_dump(++abc); //output: 124
b Decrement (--): Subtracts 1 from its operand.
$abc = 123; var_dump(--abc); //output: 122
b Unary plus (+) operator : Converts an operand to numeric (integer or float as appropriate)
- $abc = "123"; var_dump(+$abc); //output: int(123)
- $abc = 12.3; var_dump(+$abc); //output: float(12.3)
- $abc = false; var_dump(+$abc); //output: int(0)
Other operators
b Spaceship Operator (<=>): Binary comparison operator that returns -1, 0 and 1 if the first
expression is less than, equal to, or greater than the second expression.
echo 3 <=> 4, 1.1 <=> 1.1, "a" <=> "a", $abc <=> 'a'; //output: -100-1
b Not equal (<>): Binary comparison operator that returns true for inequality and false for equality
var_dump (10 <> "9"); //output: bool(true)
b Execution Operator (“): Unary operator and shorthand of shell_exec(), used to run shell
commands. Output of the command will be returned after execution.
$abc = `ls -l`; echo "$abc";
b Error control operator (@) suppresses errors if there is any and the script continues to execute.
$abc = @$bcd[$cde]; echo "abc";
$abc = @ 1/0 ; echo "output after supressing error"; //Generate error
b The @-operator works only on expressions. It can be prepended to variables, functions calls, and/or
certain language construct calls. It cannot be prepended to function or class definitions, and/or
conditional structures. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 4 / 24
Operator Unary Operator
instanceof Operator
b $object instanceof className: test whether $object is instantiated by class className or not
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 5 / 24
Operator Unary Operator
String Operator
b String concatenation
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 6 / 24
Operator Unary Operator
b Array Union operator + returns the right-hand array appended to the left-hand array; for keys that
exist in both arrays, the elements from the left-hand array will be used, and the matching elements
from the right-hand array will be ignored.
var_dump($abc + $bcd);
var_dump($bcd + $abc);
$abc = array('one','two');
$bcd = array('three','four','five');
Operator Precedence
b Rules that determine the order in which different operators are evaluated in an expression.
- The expression $a + $b * $c will be grouped as $a + ($b * $c) as the * operator has a higher
precedence than the + operator.
b When operators have equal precedence their associativity decides how the operators are grouped
- The - operator is left-associative, so $a -$b - $c is grouped as ($a - $b) - $c
- The = operator is right-associative, so $a = $b = $c is grouped as $a = ($b = $c)
b Operators of equal precedence that are non-associative cannot be used next to each other
- The expression $a < $b > $c is illegal
- The expression $a <= $b == $c is legal, because the == operator has a lower precedence than
the <= operator.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 8 / 24
Operator New concepts
b One sunny day, Ms Alice was practicing PHP, while listening to John Denver’s Take Me Home,
Country Roads. She copied the $ symbol and paste before a sequence of character to mark them as
variable, as she finds it ugly to type $ before variable names everytime. Her intention was to define
three variables with the name $abc, $bcd, and $cde that can hold character sequences. Listening and
typing in online PHP compiler ended up with the following statements
$abc = "bcd";
$$abc = "cde";
$$$abc = "def";.
On her surprise, the online compiler generates bcdcdedef as output with echo $abc, $bcd, $cde;
Now she is confused regarding the output. Explain her the reason of the output.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 9 / 24
Operator New concepts
Variable variables
b A mechanism that dynamically creates variable and access their values using the values of other
variables.
<?php
$abc = "bcd"; $$abc = "cde"; $$$abc = "def";
echo $abc, $bcd, $cde;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 10 / 24
Operator New concepts
Variable variables
b A mechanism that dynamically creates variable and access their values using the values of other
variables.
<?php
$abc = "bcd"; $$abc = "cde"; $$$abc = "def";
echo $abc, $bcd, $cde;
<?php $userPreferences = array( 'theme' => 'dark', 'language' => 'english', 'fontSize' =>
,→ 'normal');
foreach ($userPreferences as $key => $value) {
$variableName = 'user_' . $key;
$$variableName = $value;
}
echo $user_theme ."\n". $user_language ."\n". $user_fontSize;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 10 / 24
Operator New concepts
match statement
b Provides a concise and expressive way to perform conditional logic and value matching compared to
traditional switch statements or chained if-else statements.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 11 / 24
Operator New concepts
match statement
b Provides a concise and expressive way to perform conditional logic and value matching compared to
traditional switch statements or chained if-else statements.
<?php
$cCode = 'CS2031';
$cName = match ($cCode) {'CS2015' => "Web Technology", 'CS2031' => "Computer Network"};
var_dump($cName);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 11 / 24
Operator New concepts
match statement
b Provides a concise and expressive way to perform conditional logic and value matching compared to
traditional switch statements or chained if-else statements.
<?php
$cCode = 'CS2031';
$cName = match ($cCode) {'CS2015' => "Web Technology", 'CS2031' => "Computer Network"};
var_dump($cName);
<?php
$courses = ["CS2015" => "Web Technology", "CS2031" => "Computer Network", "CS2022" =>
,→ "DBMS"];
var_dump(in_array("Web Technology", $courses));
function calculateGrade($score) {
return match (true) { $score >= 90 => 'AA', $score >= 80 => 'AB', $score >= 70 => 'BB',
,→ $score >= 60 => 'BC', $score >= 50 => 'CC', $score >= 40 => 'CD', default => 'F' }; }
Control Statements
b if-else statement
$a = 5; $b = 2; $max = 0;
if (condition) {trueBlock;} if ($a > $b) {$max = $a;}
else {falseBlock;} else {$max = $b;}
print $max;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 12 / 24
Decision Control Statements-I Decision Control Statements
Control Statements
b if-else statement
$a = 5; $b = 2; $max = 0;
if (condition) {trueBlock;} if ($a > $b) {$max = $a;}
else {falseBlock;} else {$max = $b;}
print $max;
b ternary conditional statement
$a = 5; $b = 2;
(condition) ? trueValue :
$max = ( a>b ) ? a : b;
,→ falseValue;
print $max;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 12 / 24
Decision Control Statements-I Decision Control Statements
Control Statements
b if-else statement
$a = 5; $b = 2; $max = 0;
if (condition) {trueBlock;} if ($a > $b) {$max = $a;}
else {falseBlock;} else {$max = $b;}
print $max;
b ternary conditional statement
$a = 5; $b = 2;
(condition) ? trueValue :
$max = ( a>b ) ? a : b;
,→ falseValue;
print $max;
b if-else-if-else lather
$a = 5; $b = 2; $max;
if (condition1) {block1;} if ($a == $b){$max = "equal";}
else if (condition2) {block2;} else if ($a > $b) {$max = "largest";}
else {elseBlock;} else {$max = "smallest";}
print($max); . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 12 / 24
Decision Control Statements-I Decision Control Statements
Control Statements-II
b switch statement
$num = 3; $str="";
switch(expression) {
switch($num) {
case value1: {statements; break;}
case 1: {$str="One"; break;}
case value2: {statements; break;}
case 2: {$str="Two"; break;}
...... ......
case 3: {$str="Three";}
default: {statements;}
}
}
print $str;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 13 / 24
Decision Control Statements-I Decision Control Statements
Loop Statements-I
b while statement
<?php $sum = 0; $i=1;
while ($i<=10){$sum += $i; $i++;}
while (condition) {trueBlock;}
print $sum;
?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 14 / 24
Decision Control Statements-I Decision Control Statements
Loop Statements-I
b while statement
<?php $sum = 0; $i=1;
while ($i<=10){$sum += $i; $i++;}
while (condition) {trueBlock;}
print $sum;
?>
b do-while statement
<?php $sum = 0; $i=1;
do {$sum += $i; $i++;} while ($i<=10);
do {trueBlock;} while (condition);
print $sum;
?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 14 / 24
Decision Control Statements-I Decision Control Statements
Loop Statements-I
b while statement
<?php $sum = 0; $i=1;
while ($i<=10){$sum += $i; $i++;}
while (condition) {trueBlock;}
print $sum;
?>
b do-while statement
<?php $sum = 0; $i=1;
do {$sum += $i; $i++;} while ($i<=10);
do {trueBlock;} while (condition);
print $sum;
?>
b for statement
for (initialization; <?php $sum = 0;
condition; for ($i=1; $i<=10 ; $i++) $sum += $i;
post-processing) print $sum;
{trueBlock;} ?> . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 14 / 24
Decision Control Statements-I Decision Control Statements
Loop Statements-II
foreach ($array as $key => $value) <?php $shortDays = array('S' => 'Sunday', 'M' =>
{Block;} ,→ 'Monday', 'T' => 'Tuesday');
foreach($shortDays as $s => $d){
echo "Shorthand for $d is $s";
}
?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 15 / 24
Decision Control Statements-I Alternative syntax
1 <?php
1 <?php 2 $a = 2; $b = 2; $c=0;
2 if ($condition): 3 if ($a === $b):
3 /* code block */ 4 echo "Equal";
4 else: 5 echo "Extra text";
5 /* alternative block */ 6 elseif ($a != $c):
6 endif; 7 echo "Not equal";
8 echo "Extra text";
1 <?php if ($a == $b): ?> 9 else:
2 <hr>Equal</hr> 10 echo "None";
3 <?php endif; ?> 11 endif;
12 ?> . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 16 / 24
Decision Control Statements-I Alternative syntax
Multidimensional arrays
<?php $books = array(
array("title"=>"php manual","editor"=>"X","author"=>"A"),
array("title"=>"perl manual","editor"=>"Y","author"=>"B"),
array("title"=>"C manual","editor"=>"Z",author=>"C")
);
b Retrieving using for loop
<?php for ($i=0; $i < count($books); $i++ )
print "$i book, title: ".$books[$i]["title"]."\n author:
,→ ".$books[$i]["author"]."\n editor: ".$books[$i]["editor"];
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 17 / 24
Decision Control Statements-I Alternative syntax
Multidimensional arrays
<?php $books = array(
array("title"=>"php manual","editor"=>"X","author"=>"A"),
array("title"=>"perl manual","editor"=>"Y","author"=>"B"),
array("title"=>"C manual","editor"=>"Z",author=>"C")
);
b Retrieving using for loop
<?php for ($i=0; $i < count($books); $i++ )
print "$i book, title: ".$books[$i]["title"]."\n author:
,→ ".$books[$i]["author"]."\n editor: ".$books[$i]["editor"];
b Using list and each
<?php for ($i=0; $i < count($books); $i++){
print "$i book is: ";
while ( list($key,$value) = each( $books[$i] ))
print "$key: $value ";
print "\n";
}?> . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 17 / 24
Function
Introduction to Function
b Block of code that performs a specific task and can be called and executed at any point in a program.
b Provides a way to modularize code, making it easier to read, write, and maintain.
b It can return values of any data type including null using the return keyword.
b Variables defined inside a function are not visible outside of the function. Thus, scope is local.
b ? will be used before the parameter $param... to allow to pass null value.
Arrow Function
b An anonymous function with one expression and implicitly returns the value of that expression.
b Arrow functions have automatic access to the variables of the enclosing scope
$a = 2; $b = 3; $multiply = fn() => $a * $b; $multiply();
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 19 / 24
Session
Session
b A way to store data across multiple requests from the same client browser.
b When a session is started, a unique session ID is assigned to the client, which is used to identify the
client’s data on the server.
b session_start() is used to start a session
b To store data in a session $_SESSION superglobal array can be used. It behaves like a regular PHP
array, but its values are stored in the session and can be accessed across multiple requests.
b Retrieving Data from a Session is similar to retrieve data from an array.
b session_destroy() is used to end a session
<?php session_start();
$_SESSION["uName"] = "Aman";
$_SESSION["pWord"] = "amaN";
echo "User Name: " . $_SESSION["uName"] . "<br>";
echo "Password: " . $_SESSION["pWord"] . "<br>";
session_destroy();
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 20 / 24
Database connection
Create a file with the name conn.php in the server (i.e. inside /var/www/html/)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 21 / 24
Database connection Fetching data from MySql database
try {
$stmt = $conn->prepare("SELECT empID, strcat(firstName, middleName, lastName) FROM
,→ employee");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
Introduction
b Classes are fundamental to object-oriented programming, allowing encapsulation, reusability and
organization of codes. Basic class definitions begin with the keyword class, followed by a class
name. The properties and methods are enclosed with curly braces.
b $this is a pseudo-variable that refers to the current instance of the class. Typically used to access
properties and methods of the same object.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 23 / 24
Class Class
Introduction
b Classes are fundamental to object-oriented programming, allowing encapsulation, reusability and
organization of codes. Basic class definitions begin with the keyword class, followed by a class
name. The properties and methods are enclosed with curly braces.
b $this is a pseudo-variable that refers to the current instance of the class. Typically used to access
properties and methods of the same object.
<?php
class className{
public $abc = 1;
private $bcd;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 24 / 24
Class Class