SlideShare una empresa de Scribd logo
1 de 119
PHP 5
"PHP: Hypertext Preprocessor“
Vipula Dissanayake
(HDCS/HND/C.E.H/MCSE)
What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use
What You Should Already Know
 Before you continue you should have a basic understanding of the following:
 HTML
 CSS
 JavaScript
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the
browser as plain HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
PHP script starts with?
<?php
// PHP code goes here
?>
Outputting Dynamic text
echo
Request-Response Cycle
Offline Servers
• WAMP stands for
Windows/Apache / MySQL / PHP
• LAMP stands for
Linux/Apache / MySQL / PHP
XAMPP
 XAMPP is a free and open source cross-platform web server package
 X (meaning cross-platform/ multi-platform)
 Apache
 MySQL
 PHP
 Perl
A platform is a combination of hardware and software used to run software
applications.
Syntax!
 A PHP scripting block always starts with
Syntax
<?php and ends with ?>
 A PHP scripting block can be placed anywhere in the document.
Saving File
Without
PHP
code
With
PHP
code
myfile.html
myfile.php
myfile.html
myfile.php




File name . extension
Comments
 // or # to make a single-line comment
 /* and */ to make a large comment block.
 <html><body>
<?php
// This is a comment
# This is a comment
/* This is a comment block */
?>
</body></html>
Data Types
 PHP supports eight primitive types.
 boolean
 integer
 float (floating-point number, 'double')
 string
 array
 object
 resource
 NULL
Variables
 Variables are used for storing values, such as numbers, strings or function
results, so that they can be used many times in a script.
Variable Naming Rules
 All variables in PHP start with a $ sign symbol. Variables may contain strings,
numbers, or arrays.
 A variable name must start with a letter or an underscore "_“
 A variable name can only contain alpha-numeric characters and underscores
(a-Z, 0-9, and _ )
 A variable name should not contain spaces.
e.g-($myString)
Naming Rules
 If a variable name should be more than one word, it should be separated with
underscore ($my_string)
 Keywords may not be used as variable name
 Variable names are Case-sensitive
Note: abc and ABC are distinct variable names
Assigning Values To Variables
 $x=10; // numeric values
 $y=“ABC”; or $y=‘ABC’; // string values
$x = 10;
Literals are any numbers ,text, or other information that directly represent a
value
Identifier Assign Sign Literal
Predefined variables
 PHP uses predefined variables to provide access to important information
about the server and requests from a browser.
 Since version 4.1.0 of PHP, the use of the new autoglobals, also known as
superglobals, have been the recommended way to access predefined
variables
Superglobals
 $_GLOBALS
 $_SERVER
 $_GET
 $_POST
 $_COOKIE
 $_FILES
 $_ENV
 $_REQUEST
 $_SESSION
Operators
 Operators are used to manipulate or perform operations on variables and
values
Arithmetic Operators
 As the name suggests PHP arithmetic operators provide a mechanism for
performing mathematical operations:
Operator Name Example Result
+ Addition $a + $b Sum of $a and $b.
- Subtraction $a - $b Difference of $a and $b.
* Multiplication $a * $b Product of $a and $b.
/ Division $a / $b Quotient of $a and $b.
% Modulus $a % $b Remainder of $a divided by $b.
++var Pre-increment ++$a Increments $a by one, then returns $a.
var++
Post-
increment
$a++ Returns $a, then increments $a by one.
--var
Pre-
decrement
--$a Decrements $a by one, then returns $a.
Var--
Post-
decrement
$a-- Returns $a, then decrements $a by one.
Increment and decrement operators
 Prefix operators if listed before variable name
 Prefix operator is incremented by 1 before the value is assign to new variable
 Postfix operators if listed after a variable name
 Postfix operators receives the value of old variable before it is incremented
by 1
Assignment Operators
 The assignment operator is used to assign a value to a variable and is
represented by the equals (=) sign.
 The assignment operator can also be combined with arithmetic operators to
combine an assignment with a mathematical operation (for example to
multiple one value by another and assigning the result to the variable).
Operator Name Example Is The Same As
= Assignment x=y x=y
+= Addition-Assignment x+=y x=x+y
-= Subtraction-Assignment x-=y x=x-y
*= Multiplication-Assignment x*=y x=x*y
/= Division-Assignment x/=y x=x/y
%= Modulo-Assignment x%=y x=x%y
Comparison Operators
 The comparison operators provide the ability to compare one value against
another and return either a true or false result depending on the status of
the match.
 The comparison operators are used with two operands, one to the left and
one to the right of the operator.
 If you compare an integer with a string, the string is converted to a number.
If you compare two numerical strings, they are compared as integers.
Operato
r
Name Example Result
== Equal $a == $b TRUE if $a is equal to $b.
=== Identical $a === $b
TRUE if $a is equal to $b, and they
are of the same type. (introduced in
PHP 4)
!= Not equal $a != $b TRUE if $a is not equal to $b.
<> Not equal $a <> $b TRUE if $a is not equal to $b.
!== Not identical $a !== $b
TRUE if $a is not equal to $b, or they
are not of the same type. (introduced
in PHP 4)
< Less than $a < $b TRUE if $a is strictly less than $b.
> Greater than $a > $b TRUE if $a is strictly greater than $b.
<= Less than or equal to $a <= $b TRUE if $a is less than or equal to $b.
>=
Greater than or equal
to
$a >= $b
TRUE if $a is greater than or equal to
$b.
Logical Operators
 Logical Operators are also known as Boolean Operators because they evaluate
parts of an expression and return a true or false value, allowing decisions to
be made about how a script should proceed.
 Logic operators can be used to combine two or more comparison statements
combined into one statement to determine its status.
Operator Name Example Result
! Not ! $a TRUE if $a is not TRUE.
&& And $a && $b
TRUE if both $a and $b are
TRUE.
|| Or $a || $b
TRUE if either $a or $b is
TRUE.
String Operators
 The PHP String concatenation operator is used to combine values to create a
string.
 The concatenation operator is represented by a period/full stop (.) and can
be used to build a string from other strings, variables containing non-strings
(such as numbers) and even constants:
String Operators
 There are two string operators.
 The first is the concatenation operator ('.'), which returns the concatenation
of its right and left arguments.
 The second is the concatenating assignment operator ('.='), which appends the
argument on the right side to the argument on the left side.
Ex
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello
World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello
World!"
?>
Control Structures
 One of the main reasons for using scripting languages such as PHP is to build
logic and intelligence into the creation and deployment of web based data. In
order to be able to build logic into PHP based scripts, it is necessary for the
script to be able to make decisions and repeat tasks based on specified
criteria.
Control Structures
 These PHP structures can be broken down into a number of categories as
follows:
 Conditional Statements
 Switch Statements
 Looping Statements
Conditional Statements
 Conditional statements provide the core of building decision making into
scripting languages such as PHP. Conditional statements essentially control
whether a part of a script is executed depending the result of a particular
expression (i.e whether an expression returns a boolean true or false value).
Conditional Statements
 The PHP if Statement
Use this statement if you want to execute some code only if a specified
condition is true
Syntax
if (condition)
{ code to be executed if condition is true;}
If…else
 The PHP if ... else Statements
 The if statement above allows you to specify what should happen if a
particular expression evaluates to true. It does not, however, provide the
option to specify something else that should happen in the event that the
expression evaluates to be false
 If you want to execute some code if a condition is true and another code if a
condition is false, use the if....else statement.
If..else
 The PHP if ... else Statements
Syntax
if (condition)
{ code to be executed if condition is true;}
else
{ code to be executed if condition is false;}
syntax
 The PHP if ... elseif…else… Statements
Use this statement if you want to select one of many blocks of code to be
executed
Syntax
if (condition 1)
{ code to be executed if condition is true;}
elseif (condition 2)
{code to be executed if condition is true;}
elseif (condition 3)
{ code to be executed if condition is true;}
else
{ code to be executed if condition is false;}
Conditional Statements
 Switch Statements
Use this statement if you want to select one of many blocks of code to be executed
Syntax
switch(expression){
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Looping Statements
 Loop statements are the primary mechanism for telling a computer to
perform the same task over and over again until a set of criteria are met
 Loops in PHP are used to execute the same block of code a specified number
of times or while a specified condition is true.
Looping Statements
 PHP for loops
The for statement is used when you know how many times you want to
execute a statement or a list of statements.
Syntax
for (initialization; condition; increment)
{ code to be executed;}
Multiple for loop
Syntax
for (initialization 1; condition 1; increment 1){
for (initialization 2; condition 2; increment 2){
code to be executed;
}
}
The while loop
 The while loop
The while statement will execute a block of code if and as long as a condition
is true.
Syntax
while (condition){
code to be executed;
}
The do...while Statement
 The do...while Statement
The do...while statement will execute a block of code at least once - it then
will repeat the loop as long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition);
break statements
 break ends execution of the current for, foreach, while, do-while or switch
structure.
 break accepts an optional numeric argument which tells it how many nested
enclosing structures are to be broken out of.
continue statements
 continue is used within looping structures to skip the rest of the current loop
iteration and continue execution at the condition evaluation and then the
beginning of the next iteration.
 continue accepts an optional numeric argument which tells it how many
levels of enclosing loops it should skip to the end of.
return statements
 If called from within a function, the return() statement immediately ends
execution of the current function, and returns its argument as the value of
the function call. return() will also end the execution of an eval() statement
or script file.
require() & include()
 The require() statement includes and evaluates the specific file.
 require() includes and evaluates a specific file. Detailed information on how
this inclusion works is described in the documentation for include().
 include()
 The include() statement includes and evaluates the specified file.
PHP Arrays
 An array can store one or more values in a single variable name.
 PHP arrays allow you to store groups of related data in one variable (as
opposed to storing them in separate variables).
 If you want to create many similar variables, you can store the data as
elements in an array.
 Each element in the array has its own ID so that it can be easily accessed.
There are three different kind of arrays:
 Numeric array - An array with a numeric ID key
 Associative array - An array where each ID key is associated with a value
 Multidimensional array - An array containing one or more arrays
Numeric Arrays
 A numeric array stores each element with a numeric ID key.
 Can be assigned the ID key Manually or Automatically.
 Each value of the array get a unique ID which is known as INDEX NUMBER.
 Remember that the index number starts from 0.
 Assign the ID key Automatically.
Syntax
Variable = array(“elem1"," elem2"," elem3");
 element=KEY
Associative Arrays
 When storing data about specific named values, a numerical array is not
always the best way to do it.
 With associative arrays we can use the values as keys and assign values to
them.
 When we want to store elements in array with some meaningful association
other than numbers, we use associative array
Associative Arrays
 When storing data about specific named values, a numerical array is not
always the best way to do it.
 With associative arrays we can use the values as keys and assign values to
them.
 When we want to store elements in array with some meaningful association
other than numbers, we use associative array
Associative Arrays
 Syntax I
variable=array(“Ele1"=>value,“Ele2"=>value,“Ele3"=>value);
 Element names are case-sensitive, but type insensitive. It means that 'a'
differs from 'A' but '1' is the same as 1.
The foreach Statement
 The foreach statement is used to loop through arrays.
Syntax
foreach (array as value){
code to be executed ;
}
Multidimensional Arrays
 Each element in the main array can also be an array.
 And each element in the sub-array can be an array, and so on.
 A multidimensional array can contain arrays within itself and the sub arrays
contain more arrays within them
PHP Functions
 A function is a block of code that can be executed whenever we need it.
 A function is a named block of code that performs a specific task, possibly
acting upon a set of values given to it, or parameters , and possibly
returning a single value.
Functions
 Functions save on compile time—no matter how many times you call them,
functions are compiled only once for the page.
 They also improve reliability by allowing you to fix any bugs in one place,
rather than everywhere you perform a task, and they improve readability
by isolating code that performs specific tasks.
 Functions in a PHP program can be either built-in or user-defined.
 Regardless of their source, all functions are evaluated in the same way:
Create a PHP Function- user-defined
 All functions start with the word “function()”
 Name the function - It should be possible to understand what the function
does by its name. The name can start with a letter or underscore (not a
number)
 Add a "{" - The function code starts after the opening curly brace
 Insert the function code
 Add a "}" - The function is finished by a closing curly brace
Syntax
function Functionname() {
echo “Php Script";
}
// call the function
Functionname();
PHP Built-in Functions
PHP Array PHP Calendar PHP Date
PHP Error PHP Filter PHP FTP
PHP HTTP PHP Libxml PHP Mail
PHP Math PHP Misc PHPMySQL
PHP String PHP XML PHP Zip
PHP SimpleXML
PHP Filesystem
PHP Directory
Array Functions
 These functions allow you to interact with and manipulate arrays in various
ways. Arrays are essential for storing, managing, and operating on sets of
variables.
Syntax Of Array
array()
Syntax:
array(key => value)
array_count_values()
Counts all the values of an array
Syntax:
array_count_values ($input )
array_combine()
Creates an array by using one array for keys and another for its values
Syntax:
array_combine ($keys ,$values )
array_merge()
Merge one or more arrays
Syntax
array_merge ($array1 , $array2 , array $... )
array_product()
The array_product() function calculates and returns the product of an array.
Syntax:
array_product($array)
array_push()
Push one or more elements onto the end of array
Syntax
array_push ( $array , $var 1, $var2, $var... )
array_sum ()
Calculate the sum of values in an array
Syntax:
array_sum ($array )
Count()
Count elements in an array, or properties in an object
Syntax
count ($var )
array_unique()
Removes duplicate values from an array
Syntax
array_unique ( $array )
asort()
Sort an array and maintain index association
Syntax
asort ($array )
arsort()
Sort an array in reverse order and maintain index association
Syntax
arsort ($array )
ksort()
Sort an array by key
Syntax
ksort ($array )
krsort()
Sort an array by key in reverse order
Syntax
krsort ($array )
array_rand()
Pick one or more random entries out of an array
Syntax:
array_rand ( array $input [, int $num_req ] )
num_req Specifies how many entries you want to pick -if not specified, defaults
to 1.
Mathematical Functions
 These math functions will only handle values within the range of the integer
and float types on your computer
abs()
The abs() function returns the absolute value of a number.
Syntax:
abs (x)
ceil()
Returns the value of a number rounded UPWARDS to the nearest integer.
Syntax:
ceil (x)
floor()
Returns the value of a number rounded DOWNWARDS to the nearest integer.
Syntax:
floor(x)
max()
The max() function returns the number with the highest value of two
specified numbers.
Syntax:
max (x,y)
min()
The min() function returns the number with the smallest value of two
specified numbers.
Syntax:
min (x,y)
mt_rand()
Generate a better random value
Syntax
mt_rand ( int $min , int $max )
rand()
Generate a random integer
Syntax
rand ( int $min , int $max )
round()
Rounds a float
Syntax
round ($val ,$precision )
pow ()
The pow() function raises the first argument to the power of the second
argument, and returns the result.
Syntax:
pow (x,y)
sqrt()
The sqrt() function returns the square root of a number
Syntax:
sqrt(x)
Variable handling Functions
is_array()
Finds whether a variable is an array
Syntax
is_array ($var )
empty()
Determine whether a variable is empty
Syntax
empty ($var )
is_bool()
Finds out whether a variable is a boolean
Syntax
is_bool ($var )
is_float()
Finds whether the type of a variable is float
Syntax
is_float ($var )
is_int()
Find whether the type of a variable is integer
Syntax
is_int ($var )
is_numeric()
Finds whether a variable is a number or a numeric string
Syntax
is_numeric ($var )
is_string()
Find whether the type of a variable is string
Syntax
is_string ($var )
Isset()
Determine whether a variable is set
Syntax
isset ($var,$var ,$ var... )
unset()
Unset a given variable / destroys the specified variables
Syntax
unset ($var ,$var ,$var... )
var_dump()
This function displays structured information about one or more expressions that
includes its type and value
Syntax
var_dump ($expression ,$expression ,$... )
is_null()
Finds whether a variable is NULL
Syntax
is_null ($var )
String Functions
 The string functions allow you to manipulate strings.
strtoupper()
Make a string uppercase
Syntax
strtoupper ($string )
strtolower()
Make a string lowercase
Syntax
strtolower ($string )
ucwords()
Uppercase the first character of each word in a string
Syntax
ucwords ($str )
Strlen()
Get string length
Syntax
strlen ($string )
implode()
Join array elements with a string
Syntax
implode ($glue , $pieces )
explode()
Split a string by string
Syntax
explode ($delimiter , $string , $limit )
ltrim()
Strip whitespace (or other characters) from the beginning of a string
Syntax
ltrim ($str ,$charlist )
rtrim()
Strip whitespace (or other characters) from the end of a string
Syntax
rtrim ($str ,$charlist)
trim()
Strip whitespace (or other characters) from the beginning and end of a string
Syntax
trim ($str ,$charlist )
str_repeat()
Repeat a string
Syntax
str_repeat ($input , $multiplier )
str_replace()
Replace all occurrences of the search string with the replacement string
Syntax
str_replace ($search ,$replace , $subject ,$count )
str_split()
Convert a string to an array
Syntax
str_split ($string , $split_length)
str_word_count()
Return information about words used in a string
Syntax
str_word_count ($string ,$format , $charlist)
str_word_count()
Return information about words used in a string
Syntax
str_word_count ($string ,$format , $charlist)
Strpos()
Find position of first occurrence of a string
Syntax
strpos ($haystack ,$needle ,$offset )
Miscellaneous Functions
sleep()
Delay execution
Syntax
sleep(seconds)
die() or exit()
Output a message and terminate the current script
Syntax
die($message )
Syntax
exit($message )
THANK YOU

Más contenido relacionado

La actualidad más candente

Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
phelios
 

La actualidad más candente (20)

Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Data types in php
Data types in phpData types in php
Data types in php
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
php basics
php basicsphp basics
php basics
 
Php basics
Php basicsPhp basics
Php basics
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
PHP
PHP PHP
PHP
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 

Similar a Learn PHP Basics

Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 

Similar a Learn PHP Basics (20)

IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php
PhpPhp
Php
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
Variables in PHP
Variables in PHPVariables in PHP
Variables in PHP
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP MATERIAL
PHP MATERIALPHP MATERIAL
PHP MATERIAL
 
Free PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in IndiaFree PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in India
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

Learn PHP Basics

  • 1. PHP 5 "PHP: Hypertext Preprocessor“ Vipula Dissanayake (HDCS/HND/C.E.H/MCSE)
  • 2. What is PHP?  PHP is an acronym for "PHP: Hypertext Preprocessor"  PHP is a widely-used, open source scripting language  PHP scripts are executed on the server  PHP is free to download and use
  • 3. What You Should Already Know  Before you continue you should have a basic understanding of the following:  HTML  CSS  JavaScript
  • 4. What is a PHP File?  PHP files can contain text, HTML, CSS, JavaScript, and PHP code  PHP code are executed on the server, and the result is returned to the browser as plain HTML  PHP files have extension ".php"
  • 5. What Can PHP Do?  PHP can generate dynamic page content  PHP can create, open, read, write, delete, and close files on the server  PHP can collect form data  PHP can send and receive cookies  PHP can add, delete, modify data in your database  PHP can be used to control user-access  PHP can encrypt data
  • 6. PHP script starts with? <?php // PHP code goes here ?>
  • 9. Offline Servers • WAMP stands for Windows/Apache / MySQL / PHP • LAMP stands for Linux/Apache / MySQL / PHP
  • 10. XAMPP  XAMPP is a free and open source cross-platform web server package  X (meaning cross-platform/ multi-platform)  Apache  MySQL  PHP  Perl A platform is a combination of hardware and software used to run software applications.
  • 11. Syntax!  A PHP scripting block always starts with Syntax <?php and ends with ?>  A PHP scripting block can be placed anywhere in the document.
  • 13. Comments  // or # to make a single-line comment  /* and */ to make a large comment block.  <html><body> <?php // This is a comment # This is a comment /* This is a comment block */ ?> </body></html>
  • 14. Data Types  PHP supports eight primitive types.  boolean  integer  float (floating-point number, 'double')  string  array  object  resource  NULL
  • 15. Variables  Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script.
  • 16. Variable Naming Rules  All variables in PHP start with a $ sign symbol. Variables may contain strings, numbers, or arrays.  A variable name must start with a letter or an underscore "_“  A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )  A variable name should not contain spaces. e.g-($myString)
  • 17. Naming Rules  If a variable name should be more than one word, it should be separated with underscore ($my_string)  Keywords may not be used as variable name  Variable names are Case-sensitive Note: abc and ABC are distinct variable names
  • 18. Assigning Values To Variables  $x=10; // numeric values  $y=“ABC”; or $y=‘ABC’; // string values $x = 10; Literals are any numbers ,text, or other information that directly represent a value Identifier Assign Sign Literal
  • 19. Predefined variables  PHP uses predefined variables to provide access to important information about the server and requests from a browser.  Since version 4.1.0 of PHP, the use of the new autoglobals, also known as superglobals, have been the recommended way to access predefined variables
  • 20. Superglobals  $_GLOBALS  $_SERVER  $_GET  $_POST  $_COOKIE  $_FILES  $_ENV  $_REQUEST  $_SESSION
  • 21. Operators  Operators are used to manipulate or perform operations on variables and values
  • 22. Arithmetic Operators  As the name suggests PHP arithmetic operators provide a mechanism for performing mathematical operations:
  • 23. Operator Name Example Result + Addition $a + $b Sum of $a and $b. - Subtraction $a - $b Difference of $a and $b. * Multiplication $a * $b Product of $a and $b. / Division $a / $b Quotient of $a and $b. % Modulus $a % $b Remainder of $a divided by $b. ++var Pre-increment ++$a Increments $a by one, then returns $a. var++ Post- increment $a++ Returns $a, then increments $a by one. --var Pre- decrement --$a Decrements $a by one, then returns $a. Var-- Post- decrement $a-- Returns $a, then decrements $a by one.
  • 24. Increment and decrement operators  Prefix operators if listed before variable name  Prefix operator is incremented by 1 before the value is assign to new variable  Postfix operators if listed after a variable name  Postfix operators receives the value of old variable before it is incremented by 1
  • 25. Assignment Operators  The assignment operator is used to assign a value to a variable and is represented by the equals (=) sign.  The assignment operator can also be combined with arithmetic operators to combine an assignment with a mathematical operation (for example to multiple one value by another and assigning the result to the variable).
  • 26. Operator Name Example Is The Same As = Assignment x=y x=y += Addition-Assignment x+=y x=x+y -= Subtraction-Assignment x-=y x=x-y *= Multiplication-Assignment x*=y x=x*y /= Division-Assignment x/=y x=x/y %= Modulo-Assignment x%=y x=x%y
  • 27. Comparison Operators  The comparison operators provide the ability to compare one value against another and return either a true or false result depending on the status of the match.  The comparison operators are used with two operands, one to the left and one to the right of the operator.  If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers.
  • 28. Operato r Name Example Result == Equal $a == $b TRUE if $a is equal to $b. === Identical $a === $b TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4) != Not equal $a != $b TRUE if $a is not equal to $b. <> Not equal $a <> $b TRUE if $a is not equal to $b. !== Not identical $a !== $b TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4) < Less than $a < $b TRUE if $a is strictly less than $b. > Greater than $a > $b TRUE if $a is strictly greater than $b. <= Less than or equal to $a <= $b TRUE if $a is less than or equal to $b. >= Greater than or equal to $a >= $b TRUE if $a is greater than or equal to $b.
  • 29. Logical Operators  Logical Operators are also known as Boolean Operators because they evaluate parts of an expression and return a true or false value, allowing decisions to be made about how a script should proceed.  Logic operators can be used to combine two or more comparison statements combined into one statement to determine its status.
  • 30. Operator Name Example Result ! Not ! $a TRUE if $a is not TRUE. && And $a && $b TRUE if both $a and $b are TRUE. || Or $a || $b TRUE if either $a or $b is TRUE.
  • 31. String Operators  The PHP String concatenation operator is used to combine values to create a string.  The concatenation operator is represented by a period/full stop (.) and can be used to build a string from other strings, variables containing non-strings (such as numbers) and even constants:
  • 32. String Operators  There are two string operators.  The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments.  The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
  • 33. Ex <?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; // now $a contains "Hello World!" ?>
  • 34. Control Structures  One of the main reasons for using scripting languages such as PHP is to build logic and intelligence into the creation and deployment of web based data. In order to be able to build logic into PHP based scripts, it is necessary for the script to be able to make decisions and repeat tasks based on specified criteria.
  • 35. Control Structures  These PHP structures can be broken down into a number of categories as follows:  Conditional Statements  Switch Statements  Looping Statements
  • 36. Conditional Statements  Conditional statements provide the core of building decision making into scripting languages such as PHP. Conditional statements essentially control whether a part of a script is executed depending the result of a particular expression (i.e whether an expression returns a boolean true or false value).
  • 37. Conditional Statements  The PHP if Statement Use this statement if you want to execute some code only if a specified condition is true Syntax if (condition) { code to be executed if condition is true;}
  • 38. If…else  The PHP if ... else Statements  The if statement above allows you to specify what should happen if a particular expression evaluates to true. It does not, however, provide the option to specify something else that should happen in the event that the expression evaluates to be false  If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
  • 39. If..else  The PHP if ... else Statements Syntax if (condition) { code to be executed if condition is true;} else { code to be executed if condition is false;}
  • 40. syntax  The PHP if ... elseif…else… Statements Use this statement if you want to select one of many blocks of code to be executed Syntax if (condition 1) { code to be executed if condition is true;} elseif (condition 2) {code to be executed if condition is true;} elseif (condition 3) { code to be executed if condition is true;} else { code to be executed if condition is false;}
  • 41. Conditional Statements  Switch Statements Use this statement if you want to select one of many blocks of code to be executed Syntax switch(expression){ case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }
  • 42. Looping Statements  Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met  Loops in PHP are used to execute the same block of code a specified number of times or while a specified condition is true.
  • 43. Looping Statements  PHP for loops The for statement is used when you know how many times you want to execute a statement or a list of statements. Syntax for (initialization; condition; increment) { code to be executed;}
  • 44. Multiple for loop Syntax for (initialization 1; condition 1; increment 1){ for (initialization 2; condition 2; increment 2){ code to be executed; } }
  • 45. The while loop  The while loop The while statement will execute a block of code if and as long as a condition is true. Syntax while (condition){ code to be executed; }
  • 46. The do...while Statement  The do...while Statement The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. Syntax do { code to be executed; } while (condition);
  • 47. break statements  break ends execution of the current for, foreach, while, do-while or switch structure.  break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
  • 48. continue statements  continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.  continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
  • 49. return statements  If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.
  • 50. require() & include()  The require() statement includes and evaluates the specific file.  require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include().  include()  The include() statement includes and evaluates the specified file.
  • 51. PHP Arrays  An array can store one or more values in a single variable name.  PHP arrays allow you to store groups of related data in one variable (as opposed to storing them in separate variables).  If you want to create many similar variables, you can store the data as elements in an array.  Each element in the array has its own ID so that it can be easily accessed.
  • 52. There are three different kind of arrays:  Numeric array - An array with a numeric ID key  Associative array - An array where each ID key is associated with a value  Multidimensional array - An array containing one or more arrays
  • 53. Numeric Arrays  A numeric array stores each element with a numeric ID key.  Can be assigned the ID key Manually or Automatically.  Each value of the array get a unique ID which is known as INDEX NUMBER.  Remember that the index number starts from 0.  Assign the ID key Automatically. Syntax Variable = array(“elem1"," elem2"," elem3");  element=KEY
  • 54. Associative Arrays  When storing data about specific named values, a numerical array is not always the best way to do it.  With associative arrays we can use the values as keys and assign values to them.  When we want to store elements in array with some meaningful association other than numbers, we use associative array
  • 55. Associative Arrays  When storing data about specific named values, a numerical array is not always the best way to do it.  With associative arrays we can use the values as keys and assign values to them.  When we want to store elements in array with some meaningful association other than numbers, we use associative array
  • 56. Associative Arrays  Syntax I variable=array(“Ele1"=>value,“Ele2"=>value,“Ele3"=>value);  Element names are case-sensitive, but type insensitive. It means that 'a' differs from 'A' but '1' is the same as 1.
  • 57. The foreach Statement  The foreach statement is used to loop through arrays. Syntax foreach (array as value){ code to be executed ; }
  • 58. Multidimensional Arrays  Each element in the main array can also be an array.  And each element in the sub-array can be an array, and so on.  A multidimensional array can contain arrays within itself and the sub arrays contain more arrays within them
  • 59. PHP Functions  A function is a block of code that can be executed whenever we need it.  A function is a named block of code that performs a specific task, possibly acting upon a set of values given to it, or parameters , and possibly returning a single value.
  • 60. Functions  Functions save on compile time—no matter how many times you call them, functions are compiled only once for the page.  They also improve reliability by allowing you to fix any bugs in one place, rather than everywhere you perform a task, and they improve readability by isolating code that performs specific tasks.  Functions in a PHP program can be either built-in or user-defined.  Regardless of their source, all functions are evaluated in the same way:
  • 61. Create a PHP Function- user-defined  All functions start with the word “function()”  Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)  Add a "{" - The function code starts after the opening curly brace  Insert the function code  Add a "}" - The function is finished by a closing curly brace
  • 62. Syntax function Functionname() { echo “Php Script"; } // call the function Functionname();
  • 63. PHP Built-in Functions PHP Array PHP Calendar PHP Date PHP Error PHP Filter PHP FTP PHP HTTP PHP Libxml PHP Mail PHP Math PHP Misc PHPMySQL PHP String PHP XML PHP Zip PHP SimpleXML PHP Filesystem PHP Directory
  • 64. Array Functions  These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.
  • 66. array_count_values() Counts all the values of an array Syntax: array_count_values ($input )
  • 67. array_combine() Creates an array by using one array for keys and another for its values Syntax: array_combine ($keys ,$values )
  • 68. array_merge() Merge one or more arrays Syntax array_merge ($array1 , $array2 , array $... )
  • 69. array_product() The array_product() function calculates and returns the product of an array. Syntax: array_product($array)
  • 70. array_push() Push one or more elements onto the end of array Syntax array_push ( $array , $var 1, $var2, $var... )
  • 71. array_sum () Calculate the sum of values in an array Syntax: array_sum ($array )
  • 72. Count() Count elements in an array, or properties in an object Syntax count ($var )
  • 73. array_unique() Removes duplicate values from an array Syntax array_unique ( $array )
  • 74. asort() Sort an array and maintain index association Syntax asort ($array )
  • 75. arsort() Sort an array in reverse order and maintain index association Syntax arsort ($array )
  • 76. ksort() Sort an array by key Syntax ksort ($array )
  • 77. krsort() Sort an array by key in reverse order Syntax krsort ($array )
  • 78. array_rand() Pick one or more random entries out of an array Syntax: array_rand ( array $input [, int $num_req ] ) num_req Specifies how many entries you want to pick -if not specified, defaults to 1.
  • 79. Mathematical Functions  These math functions will only handle values within the range of the integer and float types on your computer
  • 80. abs() The abs() function returns the absolute value of a number. Syntax: abs (x)
  • 81. ceil() Returns the value of a number rounded UPWARDS to the nearest integer. Syntax: ceil (x)
  • 82. floor() Returns the value of a number rounded DOWNWARDS to the nearest integer. Syntax: floor(x)
  • 83. max() The max() function returns the number with the highest value of two specified numbers. Syntax: max (x,y)
  • 84. min() The min() function returns the number with the smallest value of two specified numbers. Syntax: min (x,y)
  • 85. mt_rand() Generate a better random value Syntax mt_rand ( int $min , int $max )
  • 86. rand() Generate a random integer Syntax rand ( int $min , int $max )
  • 87. round() Rounds a float Syntax round ($val ,$precision )
  • 88. pow () The pow() function raises the first argument to the power of the second argument, and returns the result. Syntax: pow (x,y)
  • 89. sqrt() The sqrt() function returns the square root of a number Syntax: sqrt(x)
  • 90. Variable handling Functions is_array() Finds whether a variable is an array Syntax is_array ($var )
  • 91. empty() Determine whether a variable is empty Syntax empty ($var )
  • 92. is_bool() Finds out whether a variable is a boolean Syntax is_bool ($var )
  • 93. is_float() Finds whether the type of a variable is float Syntax is_float ($var )
  • 94. is_int() Find whether the type of a variable is integer Syntax is_int ($var )
  • 95. is_numeric() Finds whether a variable is a number or a numeric string Syntax is_numeric ($var )
  • 96. is_string() Find whether the type of a variable is string Syntax is_string ($var )
  • 97. Isset() Determine whether a variable is set Syntax isset ($var,$var ,$ var... )
  • 98. unset() Unset a given variable / destroys the specified variables Syntax unset ($var ,$var ,$var... )
  • 99. var_dump() This function displays structured information about one or more expressions that includes its type and value Syntax var_dump ($expression ,$expression ,$... )
  • 100. is_null() Finds whether a variable is NULL Syntax is_null ($var )
  • 101. String Functions  The string functions allow you to manipulate strings.
  • 102. strtoupper() Make a string uppercase Syntax strtoupper ($string )
  • 103. strtolower() Make a string lowercase Syntax strtolower ($string )
  • 104. ucwords() Uppercase the first character of each word in a string Syntax ucwords ($str )
  • 106. implode() Join array elements with a string Syntax implode ($glue , $pieces )
  • 107. explode() Split a string by string Syntax explode ($delimiter , $string , $limit )
  • 108. ltrim() Strip whitespace (or other characters) from the beginning of a string Syntax ltrim ($str ,$charlist )
  • 109. rtrim() Strip whitespace (or other characters) from the end of a string Syntax rtrim ($str ,$charlist)
  • 110. trim() Strip whitespace (or other characters) from the beginning and end of a string Syntax trim ($str ,$charlist )
  • 112. str_replace() Replace all occurrences of the search string with the replacement string Syntax str_replace ($search ,$replace , $subject ,$count )
  • 113. str_split() Convert a string to an array Syntax str_split ($string , $split_length)
  • 114. str_word_count() Return information about words used in a string Syntax str_word_count ($string ,$format , $charlist)
  • 115. str_word_count() Return information about words used in a string Syntax str_word_count ($string ,$format , $charlist)
  • 116. Strpos() Find position of first occurrence of a string Syntax strpos ($haystack ,$needle ,$offset )
  • 118. die() or exit() Output a message and terminate the current script Syntax die($message ) Syntax exit($message )