0% found this document useful (0 votes)
14 views35 pages

WK 10 PHP Part II

The document provides an overview of PHP operators, including definitions of operators, operands, and classifications such as unary, binary, and ternary operators. It also discusses various operators like the spaceship operator, error control operator, and variable variables, along with examples of their usage. Additionally, it introduces control statements, including if-else and ternary conditional statements, and highlights the new match statement for conditional logic.

Uploaded by

vise1417
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)
14 views35 pages

WK 10 PHP Part II

The document provides an overview of PHP operators, including definitions of operators, operands, and classifications such as unary, binary, and ternary operators. It also discusses various operators like the spaceship operator, error control operator, and variable variables, along with examples of their usage. Additionally, it introduces control statements, including if-else and ternary conditional statements, and highlights the new match statement for conditional logic.

Uploaded by

vise1417
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/ 35

Web Technology

PHP

Dr. Navanath Saharia


Indian Institute of Information Technology Senapati, Manipur
nsaharia@iiitmanipur.ac.in

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
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 is applied on one operand. Example: unary +

- Binary - Operator is applied on two operands. Example: Binary +

- Ternary or tertiary - Operator is applied on three operands. Example: ? :


. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 2 / 24
Operator Unary Operator

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)

b Unary minus/negation (-): Negates its operand


- $abc = 123; var_dump(-$abc); //int(-123)

b Logical not (!): Inverts the truth value of its operand.


$abc = false; var_dump(!$abc); //output: bool(true)
b Bitwise not (∼): Inverts the bits of its operand. It operates on the binary number.
$abc = 123; var_dump(~$abc); //output: int(-124)
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 3 / 24
Operator Unary Operator

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

Array Union 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.

$abc = array("a" => "one", "b" => "two");


$bcd = array("a" => "three", "b" => "four", "c" => "five");

var_dump($abc + $bcd);
var_dump($bcd + $abc);

$abc = array('one','two');
$bcd = array('three','four','five');

var_dump ($abc + $bcd);


var_dump ($bcd + $abc);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 7 / 24
Operator Precedence

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

Alice in wonderland of PHP

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

$scores = [95, 85, 75, 65, 55];


foreach ($scores as $score) {echo "Score: $score, Grade: " . calculateGrade($score) .
. . . . . . . . . . . . . . . . . . . .
,→ "\n";} . . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 11 / 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;

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
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

b foreach statement: Works only on array and object

foreach ($array as $value) <?php $days = ['Sunday', 'Monday', 'Tuesday'];


{Block;} foreach($days as $d){
print "$d \n";
}

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

Alternative syntax for control structure


b PHP offers several alternative syntax for achieving the same functionality for constructs, such as, if,
while, for, foreach, and switch . It replaces opening curly braces { with colon : and the closing
brace to endif;, endwhile;, endfor;, endforeach;, and endswitch;
b Mixing of traditional and alternative syntax in the same control block is not supported.

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 Syntax to define a function: function functionName($param1, $param2) { statement(s) }

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 Syntax to call a function: functionName($param1, $param2);

b ? will be used before the parameter $param... to allow to pass null value.

function functionName(?string $param1, ?string $param2 = null) { }


. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 18 / 24
Function Arrow Function

Arrow Function

b An anonymous function with one expression and implicitly returns the value of that expression.

b Syntax to define a Arrow function: fn (parameters) => expression;

b Example: $multiply = fn($a, $b) => $a * $b; $multiply(2, 3)

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

Connecting MySql database

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

Fetching data from Database Using PDO


<?php include 'conn.php';
echo "<table><tr><th>empID</th><th>Name</th></tr>";

try {
$stmt = $conn->prepare("SELECT empID, strcat(firstName, middleName, lastName) FROM
,→ employee");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

foreach ($result as $row) {


echo "<tr><td>".$row[0]."</td><td>".$row[1]."</td></tr>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>"; ?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 22 / 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.

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
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;

public function functionName() {echo $this->abc;}


public function setBCD($bcd){$this->bcd = $bcd;}
public function getBCD(){return $this->bcd;}
}
$obj = new className();
$obj -> setBCD(5);
echo $obj -> getBCD(); //output: 5 . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 23 / 24
Class Class

Constructor and destructor


b Constructor: A method that is called automatically when an object of that class is created. Typically
used is to initialize the object’s properties. PHP supports one constructor per class
b Syntax: public function __construct($p1, $p2,...) {...}
b Destructor: A method that is used to release resources that an object may have acquired during its
lifetime. Typically invocation type of destructor is implicit.
b Syntax: public function __destruct() {}

. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 24 / 24
Class Class

Constructor and destructor


b Constructor: A method that is called automatically when an object of that class is created. Typically
used is to initialize the object’s properties. PHP supports one constructor per class
b Syntax: public function __construct($p1, $p2,...) {...}
b Destructor: A method that is used to release resources that an object may have acquired during its
lifetime. Typically invocation type of destructor is implicit.
b Syntax: public function __destruct() {}
<?php class className{
public $abc = 1; private $bcd;

public function __construct($abc, $bcd) {$this->abc = $abc; $this->bcd = $bcd;}


public function setBCD($bcd){$this->bcd = $bcd;}
public function getBCD(){return $this->bcd;}
public function __destruct() {echo "Destroying " . __CLASS__ . "\n";}
}
$obj = new className(2,3); echo $obj -> getBCD(); //output: 3
$obj -> setBCD(5); echo $obj -> getBCD(); //output: 5 . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
nsaharia@iiitmanipur.ac.in PHP 24 / 24

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy