SlideShare a Scribd company logo
1 of 54
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
National Diploma in Information and Communication Technology
PHP :1-INTRODUCTION>
K72C001M07 - Web Programming
23 November 2018 K72C001M07 - Web Programming / Introduction 1
Y. Achchuthan
achchuthan@slgti.com
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Syntax
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
Note: PHP statements end with a semicolon (;)
23 November 2018 K72C001M07 - Web Programming / Introduction 2
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Comments
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a
code line
$x = 5 /* + 15 */ + 5;
23 November 2018 K72C001M07 - Web Programming / Introduction 3
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.
ECHO "Hello World!<br>"; //Hello World!
echo "Hello World!<br>"; //Hello World!
EcHo "Hello World!<br>"; //Hello World!
Variable names are case-sensitive.
$color = "red";
echo "My car is " . $color . "<br>"; //My car is red
echo "My house is " . $COLOR . "<br>"; //My house is
echo "My boat is " . $coLOR . "<br>"; //My boat is
23 November 2018 K72C001M07 - Web Programming / Introduction 4
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Declaring Variables
A variable starts with the $ sign, followed by the name of the variable:
$txt = "Hello world!"; //Hello world!
$x = 5; // 5
$y = 10.5; //10.5
23 November 2018 K72C001M07 - Web Programming / Introduction 5
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Rules for variables
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different
variables)
Note: Remember that PHP variable names are case-sensitive!
23 November 2018 K72C001M07 - Web Programming / Introduction 6
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Output Variables
<?php
$txt = "W3Schools.com";
echo "I love $txt!"; // I love W3Schools.com!
$txt = "W3Schools.com";
echo "I love " . $txt . "!"; // I love
W3Schools.com!
$x = 5;
$y = 4;
echo $x + $y; //9
?>
23 November 2018 K72C001M07 - Web Programming / Introduction 7
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Exercise
• Write a PHP program to display
• your name ,
• address,
• birthday
• and school
23 November 2018 K72C001M07 - Web Programming / Introduction 8
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
23 November 2018 K72C001M07 - Web Programming / Introduction 9
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types: String
A string can be any text inside quotes. You can use single or double
quotes
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
23 November 2018 K72C001M07 - Web Programming / Introduction 10
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types: 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 three formats: decimal (10-based), hexadecimal
(16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
$x = 5985;
var_dump($x);
23 November 2018 K72C001M07 - Web Programming / Introduction 11
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types: Float and Boolean
A float (floating point number) is a number with a decimal point or a
number in exponential form.
$x = 10.365;
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
23 November 2018 K72C001M07 - Web Programming / Introduction 12
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types: Array and NULL Value
An array stores multiple values in one single variable.
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
Null is a special data type which can have only one value: NULL.
$x = "Hello world!";
$x = null;
var_dump($x);
23 November 2018 K72C001M07 - Web Programming / Introduction 13
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Data Types: Object
An object is a data type which stores data and information on how to
process that data.
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
23 November 2018 K72C001M07 - Web Programming / Introduction 14
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
String Functions
Get The Length of a String
echo strlen("Hello world!"); // 12
Count The Number of Words in a String
echo str_word_count("Hello world!"); // 2
Reverse a String
echo strrev("Hello world!"); // !dlrow olleH
Search For a Specific Text Within a String
echo strpos("Hello world!", "world"); // 6
Replace Text Within a String
echo str_replace("world", "Dolly", "Hello world!"); // Hello Dolly!
23 November 2018 K72C001M07 - Web Programming / Introduction 15
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
define(name, value, case-insensitive)
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-insensitive. Default is
false
define("GREETING", "Welcome to slgti.com!");
echo GREETING; //Welcome to slgti.com!
define("GREETING", "Welcome to slgti.com!", true);
echo greeting; //Welcome to slgti.com!
define("PI",22/7);
echo 2*PI*7;
Note: Constants are automatically global and can be used across the entire
script.
23 November 2018 K72C001M07 - Web Programming / Introduction 16
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
23 November 2018 K72C001M07 - Web Programming / Introduction 17
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction,
multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $
** Exponentiation $x ** $y $x to the $yth power
23 November 2018 K72C001M07 - Web Programming / Introduction 18
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example : Arithmetic Operators
$x = 10;
$y = 6;
echo $x + $y; //16
echo $x - $y; //4
echo $x * $y; //60
echo $x / $y; //1.6666666666667
echo $x % $y; //4
echo $x ** $y; //1000000
23 November 2018 K72C001M07 - Web Programming / Introduction 19
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Assignment Operators
The PHP assignment operators are used with numeric values to write a
value to a variable.
The basic assignment operator in PHP is "=". It means that the left
operand gets set to the value of the assignment expression on the
right.
Assignment Same as... Description
x = y x = y The left operand gets set to the
value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
23 November 2018 K72C001M07 - Web Programming / Introduction 20
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Assignment Operators
$x = 20;
$x += 100;
echo $x; //120
$x -= 30;
echo $x; //90
$y = 6;
echo $x * $y; //540
$x /= 5;
echo $x; //18
$x %= 4;
echo $x; //2
23 November 2018 K72C001M07 - Web Programming / Introduction 21
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Comparison Operators
The PHP comparison operators are used to compare two values
(number or string):
23 November 2018 K72C001M07 - Web Programming / Introduction 22
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not
of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or
equal to
$x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Comparison Operators
$x = 100;
$y = "100";
var_dump($x==$y); //boolean true
var_dump($x===$y); //boolean false
var_dump($x!=$y); //boolean false
var_dump($x<>$y); //boolean false
var_dump($x!==$y); //boolean true
$y = 50;
var_dump($x > $y); //boolean true
var_dump($x < $y); //boolean false
var_dump($x >= $y); //boolean true
var_dump($x <= $y); //boolean false
23 November 2018 K72C001M07 - Web Programming / Introduction 23
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's
value.
23 November 2018 K72C001M07 - Web Programming / Introduction 24
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Increment Operators
$x = 10;
echo ++$x; //11
echo $x++; //11
echo $x; //12
echo --$x; //11
echo $x--; //11
23 November 2018 K72C001M07 - Web Programming / Introduction 25
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Logical Operators
The PHP logical operators are used to combine conditional statements.
23 November 2018 K72C001M07 - Web Programming / Introduction 26
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Logical Operators
$x = 100;
$y = 50;
if ($x == 100 and $y == 50) {
echo "Hello world!";
} // Hello world!
if ($x == 100 xor $y == 80) {
echo "Hello world!";
} // Hello world!
if ($x == 100 || $y == 50) {
echo "Hello world!";
} // Hello world!
23 November 2018 K72C001M07 - Web Programming / Introduction 27
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
String Operators
PHP has two operators that are specially designed for strings.
• Example:
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2; //Hello world!
$txt1 .= $txt2;
echo $txt1; //Hello world!
23 November 2018 K72C001M07 - Web Programming / Introduction 28
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and
$txt2
.= Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Array Operators
The PHP array operators are used to compare arrays.
23 November 2018 K72C001M07 - Web Programming / Introduction 29
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and
of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Array Operators
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
print_r ($x + $y);
// Array ( [a] => red [b] => green [c] => blue [d] => yellow )
var_dump($x == $y); // boolean false
var_dump($x === $y); // boolean false
23 November 2018 K72C001M07 - Web Programming / Introduction 30
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Conditional Statements
• if statement - executes some code if one condition is true
• if...else statement - executes some code if a condition is true and
another code if that condition is false
• if...elseif....else statement - executes different codes for more than
two conditions
• switch statement - selects one of many blocks of code to be executed
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
23 November 2018 K72C001M07 - Web Programming / Introduction 31
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Conditional Statement
$a = 10;
$b = 20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 32
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Exercise: Conditional Statements
Write a program to show discount according to number of
books.(Number of books =15)
– 10<=books<=20 Discount-15%
– 20<books<=30 Discount-20%
– books>30 Discount-30%
23 November 2018 K72C001M07 - Web Programming / Introduction 33
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
switch Statement
Use the switch statement to select one of many blocks of code to be executed.
• Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
...
default:
code to be executed if n is different
from all labels;
}
23 November 2018 K72C001M07 - Web Programming / Introduction 34
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: switch Statement
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue
or green!";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 35
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Exercise: switch Statement
• Write PHP code for finding the number of days in a month.
• Write PHP code for display the day when give as short name of day.
(ex Mon -> Monday)
23 November 2018 K72C001M07 - Web Programming / Introduction 36
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Loops
Often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal
code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
• While- loops through a block of code as long as the specified
condition is true
• do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
23 November 2018 K72C001M07 - Web Programming / Introduction 37
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
while Loop
The while loop executes a block of code as long as the specified
condition is true.
• Syntax
while (condition is true) {
code to be executed;
}
• Example:
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
23 November 2018 K72C001M07 - Web Programming / Introduction 38
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
for Loop
The for loop is used when you know in advance how many times the
script should run.
• Syntax
for (initeger counter; test counter; increment
counter) {
code to be executed;
}
• Example:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 39
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
foreach Loop
The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.
• Syntax
foreach ($array as $value) {
code to be executed;
}
• Example:
$colors = array("red", "green", "blue",
"yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 40
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Functions
Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a
program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
• Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a
number), Function names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
23 November 2018 K72C001M07 - Web Programming / Introduction 41
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
User Defined Function
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
• we create a function named "writeMsg()".
• The opening curly brace ( { ) indicates the beginning of the function
code and the closing curly brace ( } ) indicates the end of the
function.
• The function outputs "Hello world!".
• To call the function, just write its name
23 November 2018 K72C001M07 - Web Programming / Introduction 42
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Function Arguments
function familyName1($fname) {
echo "$fname Refsnes.<br>";
}
familyName1("Jani");
familyName1("Hege");
function familyName2($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName2("Hege", "1975");
familyName2("Stale", "1978");
23 November 2018 K72C001M07 - Web Programming / Introduction 43
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Function Default Arguments
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
23 November 2018 K72C001M07 - Web Programming / Introduction 44
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Function returning values
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
23 November 2018 K72C001M07 - Web Programming / Introduction 45
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Exercise
• Write a function for +,-,* and / of two numbers and return values.
• Write separate functions for +,-,* and / of two numbers and return
values.
• Addition
• Subtraction
• Division
• Multiplication
• Modulus
23 November 2018 K72C001M07 - Web Programming / Introduction 46
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Built in Function: getdate()
Returns an associative array of information related to the timestamp. The
returning array contains ten elements with relevant information needed
when formatting a date string
• Example
$today = getdate();
print_r($today);
/* Array (
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
) */23 November 2018 K72C001M07 - Web Programming / Introduction 47
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Array
• What is an Array?
• An array is a special variable, which can hold more than one value at a time.
• Example
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and "
. $cars[2] . ".";
• Types of arrays
• Indexed arrays: Arrays with a numeric index
• Associative arrays: Arrays with named keys
• Multidimensional arrays: Arrays containing one or more arrays
23 November 2018 K72C001M07 - Web Programming / Introduction 48
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Indexed Arrays
There are two ways to create indexed arrays
• The index can be assigned automatically (index always starts at 0),
like this:
$cars = array("Volvo", "BMW", "Toyota");
• Index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
23 November 2018 K72C001M07 - Web Programming / Introduction 49
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Indexed Arrays
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and "
. $cars[2] . ".";
//Get The Length of an Array
echo count($cars);
//Loop Through an Indexed Array
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 50
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Associative Arrays
Associative arrays are arrays that use named keys that you assign to
them.
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• Assigned manually:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
23 November 2018 K72C001M07 - Web Programming / Introduction 51
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Associative Arrays
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years
old.";
//Loop Through an Associative Array
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 52
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example: Associative Arrays
//Loop Through an Associative Array
$students = array(
"name“ => "Saman",
"address“ => "Kandy Rd, Malabe",
"tp“ => “(+94) 812 56789",
"email“ => "saman@slgti.com"
);
foreach($students as $key=>$value) {
echo "$key = $value","<BR>";
}
23 November 2018 K72C001M07 - Web Programming / Introduction 53
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Reference
www.w3schools.com
www.php.net
23 November 2018 K72C001M07 - Web Programming / Introduction 54

More Related Content

What's hot (11)

Lecture1
Lecture1Lecture1
Lecture1
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Programming in c
Programming in cProgramming in c
Programming in c
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
 
basics of c++
basics of c++basics of c++
basics of c++
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
26 Jo P Feb 09
26 Jo P Feb 0926 Jo P Feb 09
26 Jo P Feb 09
 
Cling the llvm based interpreter
Cling the llvm based interpreterCling the llvm based interpreter
Cling the llvm based interpreter
 
C vs c++
C vs c++C vs c++
C vs c++
 
C vs c++
C vs c++C vs c++
C vs c++
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to PHP-introduction

PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for GraphsJean Ihm
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template EnginesEfficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Enginesadonatwork
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Roel Hartman
 
XQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) languageXQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) languagejimfuller2009
 
VSSML18. REST API and Bindings
VSSML18. REST API and BindingsVSSML18. REST API and Bindings
VSSML18. REST API and BindingsBigML, Inc
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Naveen Kumar
 
Hivemall meets Digdag @Hackertackle 2018-02-17
Hivemall meets Digdag @Hackertackle 2018-02-17Hivemall meets Digdag @Hackertackle 2018-02-17
Hivemall meets Digdag @Hackertackle 2018-02-17Makoto Yui
 
Big Data, Bigger Analytics
Big Data, Bigger AnalyticsBig Data, Bigger Analytics
Big Data, Bigger AnalyticsItzhak Kameli
 
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.Anton Mishchuk
 
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukElixir Club
 
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adder
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adderFpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adder
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adderMalik Tauqir Hasan
 
educational course/tutorialoutlet.com
educational course/tutorialoutlet.comeducational course/tutorialoutlet.com
educational course/tutorialoutlet.comjorge0043
 

Similar to PHP-introduction (20)

PHP Form Handling
PHP Form HandlingPHP Form Handling
PHP Form Handling
 
PRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdfPRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdf
 
3 php-connect-to-my sql
3 php-connect-to-my sql3 php-connect-to-my sql
3 php-connect-to-my sql
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for Graphs
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template EnginesEfficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Engines
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
 
XQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) languageXQuery - The GSD (Getting Stuff Done) language
XQuery - The GSD (Getting Stuff Done) language
 
More about PHP
More about PHPMore about PHP
More about PHP
 
VSSML18. REST API and Bindings
VSSML18. REST API and BindingsVSSML18. REST API and Bindings
VSSML18. REST API and Bindings
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3
 
Hivemall meets Digdag @Hackertackle 2018-02-17
Hivemall meets Digdag @Hackertackle 2018-02-17Hivemall meets Digdag @Hackertackle 2018-02-17
Hivemall meets Digdag @Hackertackle 2018-02-17
 
Big Data, Bigger Analytics
Big Data, Bigger AnalyticsBig Data, Bigger Analytics
Big Data, Bigger Analytics
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.
 
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton MishchukFlowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
 
Java script
Java scriptJava script
Java script
 
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adder
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adderFpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adder
Fpga 07-port-rules-gate-delay-data-flow-carry-look-ahead-adder
 
educational course/tutorialoutlet.com
educational course/tutorialoutlet.comeducational course/tutorialoutlet.com
educational course/tutorialoutlet.com
 
JavaScript
JavaScriptJavaScript
JavaScript
 

More from Achchuthan Yogarajah

Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Achchuthan Yogarajah
 
PADDY CULTIVATION MANAGEMENT SYSTEM
PADDY CULTIVATION MANAGEMENT  SYSTEMPADDY CULTIVATION MANAGEMENT  SYSTEM
PADDY CULTIVATION MANAGEMENT SYSTEMAchchuthan Yogarajah
 
Statistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationStatistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationAchchuthan Yogarajah
 
Greedy Knapsack Problem - by Y Achchuthan
Greedy Knapsack Problem  - by Y AchchuthanGreedy Knapsack Problem  - by Y Achchuthan
Greedy Knapsack Problem - by Y AchchuthanAchchuthan Yogarajah
 

More from Achchuthan Yogarajah (9)

Managing the design process
Managing the design processManaging the design process
Managing the design process
 
intoduction to network devices
intoduction to network devicesintoduction to network devices
intoduction to network devices
 
basic network concepts
basic network conceptsbasic network concepts
basic network concepts
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
 
Introduction to Web Programming
Introduction to Web Programming Introduction to Web Programming
Introduction to Web Programming
 
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
 
PADDY CULTIVATION MANAGEMENT SYSTEM
PADDY CULTIVATION MANAGEMENT  SYSTEMPADDY CULTIVATION MANAGEMENT  SYSTEM
PADDY CULTIVATION MANAGEMENT SYSTEM
 
Statistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationStatistical Machine Translation for Language Localisation
Statistical Machine Translation for Language Localisation
 
Greedy Knapsack Problem - by Y Achchuthan
Greedy Knapsack Problem  - by Y AchchuthanGreedy Knapsack Problem  - by Y Achchuthan
Greedy Knapsack Problem - by Y Achchuthan
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

PHP-introduction

  • 1. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology National Diploma in Information and Communication Technology PHP :1-INTRODUCTION> K72C001M07 - Web Programming 23 November 2018 K72C001M07 - Web Programming / Introduction 1 Y. Achchuthan achchuthan@slgti.com
  • 2. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Syntax A PHP script starts with <?php and ends with ?>: <?php // PHP code goes here ?> The default file extension for PHP files is ".php". Note: PHP statements end with a semicolon (;) 23 November 2018 K72C001M07 - Web Programming / Introduction 2
  • 3. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Comments // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ // You can also use comments to leave out parts of a code line $x = 5 /* + 15 */ + 5; 23 November 2018 K72C001M07 - Web Programming / Introduction 3
  • 4. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Case Sensitivity In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. ECHO "Hello World!<br>"; //Hello World! echo "Hello World!<br>"; //Hello World! EcHo "Hello World!<br>"; //Hello World! Variable names are case-sensitive. $color = "red"; echo "My car is " . $color . "<br>"; //My car is red echo "My house is " . $COLOR . "<br>"; //My house is echo "My boat is " . $coLOR . "<br>"; //My boat is 23 November 2018 K72C001M07 - Web Programming / Introduction 4
  • 5. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Declaring Variables A variable starts with the $ sign, followed by the name of the variable: $txt = "Hello world!"; //Hello world! $x = 5; // 5 $y = 10.5; //10.5 23 November 2018 K72C001M07 - Web Programming / Introduction 5
  • 6. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Rules for variables • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive ($age and $AGE are two different variables) Note: Remember that PHP variable names are case-sensitive! 23 November 2018 K72C001M07 - Web Programming / Introduction 6
  • 7. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Output Variables <?php $txt = "W3Schools.com"; echo "I love $txt!"; // I love W3Schools.com! $txt = "W3Schools.com"; echo "I love " . $txt . "!"; // I love W3Schools.com! $x = 5; $y = 4; echo $x + $y; //9 ?> 23 November 2018 K72C001M07 - Web Programming / Introduction 7
  • 8. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Exercise • Write a PHP program to display • your name , • address, • birthday • and school 23 November 2018 K72C001M07 - Web Programming / Introduction 8
  • 9. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types PHP supports the following data types: • String • Integer • Float (floating point numbers - also called double) • Boolean • Array • Object • NULL • Resource 23 November 2018 K72C001M07 - Web Programming / Introduction 9
  • 10. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types: String A string can be any text inside quotes. You can use single or double quotes $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; 23 November 2018 K72C001M07 - Web Programming / Introduction 10
  • 11. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types: 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 three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0) $x = 5985; var_dump($x); 23 November 2018 K72C001M07 - Web Programming / Introduction 11
  • 12. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types: Float and Boolean A float (floating point number) is a number with a decimal point or a number in exponential form. $x = 10.365; A Boolean represents two possible states: TRUE or FALSE. $x = true; $y = false; 23 November 2018 K72C001M07 - Web Programming / Introduction 12
  • 13. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types: Array and NULL Value An array stores multiple values in one single variable. $cars = array("Volvo","BMW","Toyota"); var_dump($cars); Null is a special data type which can have only one value: NULL. $x = "Hello world!"; $x = null; var_dump($x); 23 November 2018 K72C001M07 - Web Programming / Introduction 13
  • 14. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Data Types: Object An object is a data type which stores data and information on how to process that data. class Car { function Car() { $this->model = "VW"; } } // create an object $herbie = new Car(); // show object properties echo $herbie->model; 23 November 2018 K72C001M07 - Web Programming / Introduction 14
  • 15. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology String Functions Get The Length of a String echo strlen("Hello world!"); // 12 Count The Number of Words in a String echo str_word_count("Hello world!"); // 2 Reverse a String echo strrev("Hello world!"); // !dlrow olleH Search For a Specific Text Within a String echo strpos("Hello world!", "world"); // 6 Replace Text Within a String echo str_replace("world", "Dolly", "Hello world!"); // Hello Dolly! 23 November 2018 K72C001M07 - Web Programming / Introduction 15
  • 16. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Constants A constant is an identifier (name) for a simple value. The value cannot be changed during the script. define(name, value, case-insensitive) • name: Specifies the name of the constant • value: Specifies the value of the constant • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false define("GREETING", "Welcome to slgti.com!"); echo GREETING; //Welcome to slgti.com! define("GREETING", "Welcome to slgti.com!", true); echo greeting; //Welcome to slgti.com! define("PI",22/7); echo 2*PI*7; Note: Constants are automatically global and can be used across the entire script. 23 November 2018 K72C001M07 - Web Programming / Introduction 16
  • 17. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Operators Operators are used to perform operations on variables and values. PHP divides the operators in the following groups: • Arithmetic operators • Assignment operators • Comparison operators • Increment/Decrement operators • Logical operators • String operators • Array operators 23 November 2018 K72C001M07 - Web Programming / Introduction 17
  • 18. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Arithmetic Operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $ ** Exponentiation $x ** $y $x to the $yth power 23 November 2018 K72C001M07 - Web Programming / Introduction 18
  • 19. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example : Arithmetic Operators $x = 10; $y = 6; echo $x + $y; //16 echo $x - $y; //4 echo $x * $y; //60 echo $x / $y; //1.6666666666667 echo $x % $y; //4 echo $x ** $y; //1000000 23 November 2018 K72C001M07 - Web Programming / Introduction 19
  • 20. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Assignment Operators The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus 23 November 2018 K72C001M07 - Web Programming / Introduction 20
  • 21. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Assignment Operators $x = 20; $x += 100; echo $x; //120 $x -= 30; echo $x; //90 $y = 6; echo $x * $y; //540 $x /= 5; echo $x; //18 $x %= 4; echo $x; //2 23 November 2018 K72C001M07 - Web Programming / Introduction 21
  • 22. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Comparison Operators The PHP comparison operators are used to compare two values (number or string): 23 November 2018 K72C001M07 - Web Programming / Introduction 22 Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y <> Not equal $x <> $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
  • 23. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Comparison Operators $x = 100; $y = "100"; var_dump($x==$y); //boolean true var_dump($x===$y); //boolean false var_dump($x!=$y); //boolean false var_dump($x<>$y); //boolean false var_dump($x!==$y); //boolean true $y = 50; var_dump($x > $y); //boolean true var_dump($x < $y); //boolean false var_dump($x >= $y); //boolean true var_dump($x <= $y); //boolean false 23 November 2018 K72C001M07 - Web Programming / Introduction 23
  • 24. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Increment / Decrement Operators The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value. 23 November 2018 K72C001M07 - Web Programming / Introduction 24 Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one
  • 25. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Increment Operators $x = 10; echo ++$x; //11 echo $x++; //11 echo $x; //12 echo --$x; //11 echo $x--; //11 23 November 2018 K72C001M07 - Web Programming / Introduction 25
  • 26. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Logical Operators The PHP logical operators are used to combine conditional statements. 23 November 2018 K72C001M07 - Web Programming / Introduction 26 Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true
  • 27. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Logical Operators $x = 100; $y = 50; if ($x == 100 and $y == 50) { echo "Hello world!"; } // Hello world! if ($x == 100 xor $y == 80) { echo "Hello world!"; } // Hello world! if ($x == 100 || $y == 50) { echo "Hello world!"; } // Hello world! 23 November 2018 K72C001M07 - Web Programming / Introduction 27
  • 28. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology String Operators PHP has two operators that are specially designed for strings. • Example: $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2; //Hello world! $txt1 .= $txt2; echo $txt1; //Hello world! 23 November 2018 K72C001M07 - Web Programming / Introduction 28 Operator Name Example Result . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
  • 29. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Array Operators The PHP array operators are used to compare arrays. 23 November 2018 K72C001M07 - Web Programming / Introduction 29 Operator Name Example Result + Union $x + $y Union of $x and $y == Equality $x == $y Returns true if $x and $y have the same key/value pairs === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types != Inequality $x != $y Returns true if $x is not equal to $y <> Inequality $x <> $y Returns true if $x is not equal to $y !== Non-identity $x !== $y Returns true if $x is not identical to $y
  • 30. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Array Operators $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); print_r ($x + $y); // Array ( [a] => red [b] => green [c] => blue [d] => yellow ) var_dump($x == $y); // boolean false var_dump($x === $y); // boolean false 23 November 2018 K72C001M07 - Web Programming / Introduction 30
  • 31. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Conditional Statements • if statement - executes some code if one condition is true • if...else statement - executes some code if a condition is true and another code if that condition is false • if...elseif....else statement - executes different codes for more than two conditions • switch statement - selects one of many blocks of code to be executed Syntax if (condition) { code to be executed if this condition is true; } elseif (condition) { code to be executed if this condition is true; } else { code to be executed if all conditions are false; } 23 November 2018 K72C001M07 - Web Programming / Introduction 31
  • 32. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Conditional Statement $a = 10; $b = 20; if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 32
  • 33. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Exercise: Conditional Statements Write a program to show discount according to number of books.(Number of books =15) – 10<=books<=20 Discount-15% – 20<books<=30 Discount-20% – books>30 Discount-30% 23 November 2018 K72C001M07 - Web Programming / Introduction 33
  • 34. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology switch Statement Use the switch statement to select one of many blocks of code to be executed. • Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; ... default: code to be executed if n is different from all labels; } 23 November 2018 K72C001M07 - Web Programming / Introduction 34
  • 35. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: switch Statement $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue or green!"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 35
  • 36. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Exercise: switch Statement • Write PHP code for finding the number of days in a month. • Write PHP code for display the day when give as short name of day. (ex Mon -> Monday) 23 November 2018 K72C001M07 - Web Programming / Introduction 36
  • 37. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements: • While- loops through a block of code as long as the specified condition is true • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true • for - loops through a block of code a specified number of times • foreach - loops through a block of code for each element in an array 23 November 2018 K72C001M07 - Web Programming / Introduction 37
  • 38. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology while Loop The while loop executes a block of code as long as the specified condition is true. • Syntax while (condition is true) { code to be executed; } • Example: $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } 23 November 2018 K72C001M07 - Web Programming / Introduction 38
  • 39. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology for Loop The for loop is used when you know in advance how many times the script should run. • Syntax for (initeger counter; test counter; increment counter) { code to be executed; } • Example: for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 39
  • 40. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. • Syntax foreach ($array as $value) { code to be executed; } • Example: $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 40
  • 41. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Functions Besides the built-in PHP functions, we can create our own functions. • A function is a block of statements that can be used repeatedly in a program. • A function will not execute immediately when a page loads. • A function will be executed by a call to the function. • Syntax function functionName() { code to be executed; } Note: A function name can start with a letter or underscore (not a number), Function names are NOT case-sensitive. Tip: Give the function a name that reflects what the function does! 23 November 2018 K72C001M07 - Web Programming / Introduction 41
  • 42. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology User Defined Function function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function • we create a function named "writeMsg()". • The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. • The function outputs "Hello world!". • To call the function, just write its name 23 November 2018 K72C001M07 - Web Programming / Introduction 42
  • 43. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Function Arguments function familyName1($fname) { echo "$fname Refsnes.<br>"; } familyName1("Jani"); familyName1("Hege"); function familyName2($fname, $year) { echo "$fname Refsnes. Born in $year <br>"; } familyName2("Hege", "1975"); familyName2("Stale", "1978"); 23 November 2018 K72C001M07 - Web Programming / Introduction 43
  • 44. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Function Default Arguments function setHeight($minheight = 50) { echo "The height is : $minheight <br>"; } setHeight(350); setHeight(); // will use the default value of 50 setHeight(135); setHeight(80); 23 November 2018 K72C001M07 - Web Programming / Introduction 44
  • 45. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Function returning values function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5, 10) . "<br>"; echo "7 + 13 = " . sum(7, 13) . "<br>"; echo "2 + 4 = " . sum(2, 4); 23 November 2018 K72C001M07 - Web Programming / Introduction 45
  • 46. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Exercise • Write a function for +,-,* and / of two numbers and return values. • Write separate functions for +,-,* and / of two numbers and return values. • Addition • Subtraction • Division • Multiplication • Modulus 23 November 2018 K72C001M07 - Web Programming / Introduction 46
  • 47. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Built in Function: getdate() Returns an associative array of information related to the timestamp. The returning array contains ten elements with relevant information needed when formatting a date string • Example $today = getdate(); print_r($today); /* Array ( [seconds] => 40 [minutes] => 58 [hours] => 21 [mday] => 17 [wday] => 2 [mon] => 6 [year] => 2003 [yday] => 167 [weekday] => Tuesday [month] => June [0] => 1055901520 ) */23 November 2018 K72C001M07 - Web Programming / Introduction 47
  • 48. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Array • What is an Array? • An array is a special variable, which can hold more than one value at a time. • Example $cars = array("Volvo", "BMW", "Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; • Types of arrays • Indexed arrays: Arrays with a numeric index • Associative arrays: Arrays with named keys • Multidimensional arrays: Arrays containing one or more arrays 23 November 2018 K72C001M07 - Web Programming / Introduction 48
  • 49. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Indexed Arrays There are two ways to create indexed arrays • The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); • Index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota"; 23 November 2018 K72C001M07 - Web Programming / Introduction 49
  • 50. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Indexed Arrays $cars = array("Volvo", "BMW", "Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; //Get The Length of an Array echo count($cars); //Loop Through an Indexed Array $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 50
  • 51. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Associative Arrays Associative arrays are arrays that use named keys that you assign to them. • There are two ways to create an associative array: $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); • Assigned manually: $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43"; 23 November 2018 K72C001M07 - Web Programming / Introduction 51
  • 52. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Associative Arrays $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; //Loop Through an Associative Array foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 52
  • 53. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example: Associative Arrays //Loop Through an Associative Array $students = array( "name“ => "Saman", "address“ => "Kandy Rd, Malabe", "tp“ => “(+94) 812 56789", "email“ => "saman@slgti.com" ); foreach($students as $key=>$value) { echo "$key = $value","<BR>"; } 23 November 2018 K72C001M07 - Web Programming / Introduction 53
  • 54. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Reference www.w3schools.com www.php.net 23 November 2018 K72C001M07 - Web Programming / Introduction 54