SlideShare une entreprise Scribd logo
1  sur  21
PHP Basic
Khem Puthea
putheakhemdeveloper@gmail.com
Part I: Understanding PHP Basics
Using Variables and Operators
Prepared by KhmerCourse
Storing Data in Variables
៚ Some simple rules for naming variables
៙ Be preceded with a dollar symbol $
៙ And begin with a letter or underscore _
៙ Optionally followed by more letters, numbers, or underscore
៙ Be not permitted
ៜ Punctuation: commas ,, quotation marks ?, or periods .
ៜ Spaces
៙ e.g.
ៜ $id, $_name and $query3: valid
ៜ $96, $day. and email: invalid
៚ Variable names are case-sensitive.
៙ e.g. $name and $Name refer to different variables.
3
Assigning Values to Variables
៚ $var = val;
៙ e.g. assigningValues2Variables.php
<?php $language = "PHP"; ?>
<h1>Welcome <?php echo $language; ?></h1>
៚ Dynamic variable's name
៙ e.g. dynamicVariableName.php
<?php
$clone = "real";
// create a
value of
${$clone} =
echo $real;
?>
new variable dynamically
$clone
"REAL";
// output: REAL
at run time from the
Is it possible for a variable's name itself to be a variable?
៚ echo(): print the value of a variable
4
Destroying Variables
៚ e.g. destroyingVariables.php
<?php
$apple = "Apple";
echo $apple; // output: Apple
// unset()
unset($apple);
echo $apple; // error: Undefined variable
$banana = "Banana";
echo $banana; //
// NULL value
$banana = NULL;
echo $banana; //
?>
output: Banana
output: (nothing)
5
Inspecting Variable Contents
៚ e.g. inspectingVariableContents.php
<?php
$apple = "Apple"; $yr = 2011;
// var_dump()
var_dump($apple);
var_dump($yr); //
// output: string(5)
output: int(2011)
"Apple"
// print_r()
print_r($apple); // output: Apple
print_r($yr);
?>
// output: 2011
6
Understanding PHP’s Data Types
៚ Data type is the values assigned to a variable.
៚ Booleans
៙ 1 (true) or 0 (false)
៚ 2 numeric
៙ Floating-point values (a.k.a floats or doubles) are decimal or fractional
numbers,
៙ While integers are round numbers.
៚ Non-numeric: String
៙ Be enclosed in single quotes (') or double quotes (")
៚ NULL (a special data type in PHP4)
៙ Represent empty variables; a variable of type NULL is a variable without
any data.
A NULL value is not equivalent to an empty string "".
7
Understanding PHP’s Data Types (cont.)
៚ e.g. hexadecimal_octal_scientificNotation.php
<?php
$dec
echo
= 8; // decimal
$dec; // output: 8
$oct
echo
= 010; // octal
$oct; // output: 8
$hex
echo
= 0x5dc;
$hex; //
// hexadecimal
output: 1500
// scientific notation
$sn1
$sn2
echo
?>
= 6.9e+2;
= 6.9e-2;
$sn1." ".$sn2; // output: 690 0.069
8
Setting and Checking Variable Data Types
៚ e.g. setting_CheckingVariableDataTypes.php
<?php
$apple = "Apple";
echo gettype($apple); // output: string
$yr = 2011;
echo gettype($yr); // output: integer
$valid = true;
echo gettype($valid); // output : boolean
echo gettype($banana); // output: NULL
variable)
(error: Undefined
$empty = NULL;
echo gettype($empty); // output: NULL
?>
9
Setting and Checking Variable Data Types (cont.)
៚ e.g. casting.php
<?php
$f_speed =
$i_speed =
// output:
36.9; // floating-point
(integer)
36.9
$f_speed; // cast to integer
echo $f_speed;
// output: 36
echo
?>
$i_speed;;
10
Data Type Checking Functions
Function Purpose
is_bool Test if holding a Boolean value
is_numeric Test if holding a numeric value
is_int Test if holding an integer value
is_float Test if holding a float value
is_string Test if holding a string value
is_null Test if holding a NULL value
is_array Test if being an array
is_object Test if being an object
Using Constants
៚ define(CONST, val);
៚ Constant names follows the same rules as variable names but not the $
៚ e.g. usingConstants.php
<?php
define("APPLE", "Apple");
define("YR", 2011);
prefix.
// output: Apple 2011
echo
?>
APPLE." ".YR;
Constants name are usually entirely UPPERCASED.
When should we use a variable, and when should we use a constant?
11
Manipulating Variables with Operators
៚ Operators are symbols that tell the PHP processor to perform certain actions.
៚ PHP supports more than 50 such operators, ranging from operators for
arithmetical operations to operators for logical comparison and bitwise
calculations.
12
Performing Arithmetic Operations
៚ e.g. arithmeticOperations.php
<?php
echo 3 + 2; // output: 5
echo 3 - 2; // output: 1
echo 3 * 2; // output: 6
echo 3 / 2; // output: 1.5
echo
?>
3 % 2; // output: 1
Is there any limit on how large a PHP integer value can be?
13
Arithmetic Operators
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulus
Concatenating Strings
៚ e.g. concatenatingStrings.php
<?php
$apple = "Apple";
$banana = "Banana";
// use (.) to join strings into 1
$fruits = $apple." and ".$banana;
// output: I love apple and
".$fruits.".";
banana..
echo
?>
"I love
14
Comparing Variables
៚ e.g. comparingVariables.php
<?php
$num = 6; $num2 = 3; $str = "6";
// output:
echo ($num
// output:
echo ($num
0
<
1
>
(false)
$num2);
(true)
$num2);
// output:
echo ($num
0
<
(false)
$str);
// output:
echo ($num
// output:
echo ($num
?>
1 (true)
== $str);
0 (false)
=== $str);
15
Comparison Operators
Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type
Performing Logical Tests
៚ e.g. performingLogicalTests.php
<?php
// output:
echo (true
// output:
echo (true
// output:
1 (true)
&& true);
0 (false)
&& false);
0 (false)
echo (false && false);
// output: 1 (true)
echo (false || true);
// output: 0 (false)
echo (!true);
?>
16
Logical Operators
Operator Description
&& AND
|| OR
! NOT
Other Useful Operators
៚ e.g. otherUsefulOperators.php
<?php
$count = 7; $age = 60; $greet = "We";
Increased by 1: ++
Decreased by 1: --
$count -= 2;
// output: 5
echo $count;
e.g. $count++; // $count = $count + 1;
$age /= 5;
// output: 12
echo $age;
$greet .= "lcome!";
// output: Welcome!
echo $greet;
?>
17
Assignment Operators
Operator Description
+= Add, assign
-= Subtract, assign
*= Multiply, assign
/= Divide, assign
%= Modulus, assign
.= Concatenate, assign
Understanding Operator Precedence
៚ Operators at the same level have equal precedence:
៙ ++
៙ !
៙ *
៙ +
៙ <
៙ ==
៙ &&
៙ ||
៙ =
--
/
-
<=
!=
%
.
> >=
=== !==
+= -= *= /= .= %= &= |= ^=
៚ Parentheses (
៚ e.g.
៙ 3 + 2 *
៙ (3 + 2)
): force PHP to evaluate it first
5; // 3 + 10 = 13
* 5; // 5 * 5 = 25
18
Handling Form Input
៚ e.g. chooseCar.html
<form name="fCar" method="POST" action="getCar.php">
<select name="selType">
<option value="Porsche">Porsche</option>
<option value="Ford">Ford</option>
</select>
Color:
<input
<input
</form>
type="text" name="txtColor" />
type="submit" value="get Car" />
action="getCar.php"
Reference a PHP script
method="POST"
Submission via POST
GET: method="GET"
19
Handling Form Input (cont.)
៚ e.g. getCar.php
<?php
// get values via $_POST | $_GET
$type = $_POST["selType"];
$color = $_POST["txtColor"];
echo $color." ".$type;
?>
$_POST[fieldName];
$_POST: a special container variable (array) is used to get a value of a field
of a form sent by using the POST method (or $_GET for the GET method).
fieldName: the field whose value will be get/assigned to a variable.
20
The End
21
The End

Contenu connexe

Tendances

Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 

Tendances (20)

Php variables
Php variablesPhp variables
Php variables
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Operators php
Operators phpOperators php
Operators php
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php
PhpPhp
Php
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Php functions
Php functionsPhp functions
Php functions
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Php basics
Php basicsPhp basics
Php basics
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Php tutorial
Php  tutorialPhp  tutorial
Php tutorial
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
PHP
PHPPHP
PHP
 
Php
PhpPhp
Php
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 

En vedette

OICX Retail Customer Experience
OICX Retail Customer ExperienceOICX Retail Customer Experience
OICX Retail Customer Experience
Damian Kernahan
 
Monomictic lakes francisco muñoz maestre
Monomictic lakes francisco muñoz maestreMonomictic lakes francisco muñoz maestre
Monomictic lakes francisco muñoz maestre
Francisco Maestre
 
Hybrid-Active-Optical-Cable-White-Paper
Hybrid-Active-Optical-Cable-White-PaperHybrid-Active-Optical-Cable-White-Paper
Hybrid-Active-Optical-Cable-White-Paper
Nguyen Nguyen
 

En vedette (20)

Sign up github
Sign up githubSign up github
Sign up github
 
Introduction to css part1
Introduction to css part1Introduction to css part1
Introduction to css part1
 
Membuat partisi di os windows
Membuat partisi di os windowsMembuat partisi di os windows
Membuat partisi di os windows
 
Facebook Tackle Box: 10 Apps & Tools Every Brand Should Use
Facebook Tackle Box: 10 Apps & Tools Every Brand Should UseFacebook Tackle Box: 10 Apps & Tools Every Brand Should Use
Facebook Tackle Box: 10 Apps & Tools Every Brand Should Use
 
Q2 2013 ASSA ABLOY investors presentation 19 july
Q2 2013 ASSA ABLOY investors presentation 19 julyQ2 2013 ASSA ABLOY investors presentation 19 july
Q2 2013 ASSA ABLOY investors presentation 19 july
 
C53200
C53200C53200
C53200
 
srgoc
srgocsrgoc
srgoc
 
2
22
2
 
Numeración romana
Numeración romanaNumeración romana
Numeración romana
 
Time Management within IT Project Management
Time Management within IT Project ManagementTime Management within IT Project Management
Time Management within IT Project Management
 
Granada425
Granada425Granada425
Granada425
 
Caring for Sharring
 Caring for Sharring  Caring for Sharring
Caring for Sharring
 
OICX Retail Customer Experience
OICX Retail Customer ExperienceOICX Retail Customer Experience
OICX Retail Customer Experience
 
Monomictic lakes francisco muñoz maestre
Monomictic lakes francisco muñoz maestreMonomictic lakes francisco muñoz maestre
Monomictic lakes francisco muñoz maestre
 
Abc c program
Abc c programAbc c program
Abc c program
 
Hybrid-Active-Optical-Cable-White-Paper
Hybrid-Active-Optical-Cable-White-PaperHybrid-Active-Optical-Cable-White-Paper
Hybrid-Active-Optical-Cable-White-Paper
 
Ngaputaw ppt
Ngaputaw pptNgaputaw ppt
Ngaputaw ppt
 
Statement to Guardian
Statement to GuardianStatement to Guardian
Statement to Guardian
 
Aula 1 a obra de kant como síntese do nascente pensamento burguês
Aula 1   a obra de kant como síntese do nascente pensamento burguêsAula 1   a obra de kant como síntese do nascente pensamento burguês
Aula 1 a obra de kant como síntese do nascente pensamento burguês
 
Sun & VMware Desktop Training
Sun & VMware Desktop TrainingSun & VMware Desktop Training
Sun & VMware Desktop Training
 

Similaire à Php using variables-operators

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
 
Web app development_php_05
Web app development_php_05Web app development_php_05
Web app development_php_05
Hassen Poreya
 

Similaire à Php using variables-operators (20)

Php introduction
Php introductionPhp introduction
Php introduction
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
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 Basics
PHP BasicsPHP Basics
PHP Basics
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Php
PhpPhp
Php
 
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
 
Web app development_php_05
Web app development_php_05Web app development_php_05
Web app development_php_05
 
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
 

Dernier

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Dernier (20)

Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
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
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
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.
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

Php using variables-operators

  • 2. Part I: Understanding PHP Basics Using Variables and Operators Prepared by KhmerCourse
  • 3. Storing Data in Variables ៚ Some simple rules for naming variables ៙ Be preceded with a dollar symbol $ ៙ And begin with a letter or underscore _ ៙ Optionally followed by more letters, numbers, or underscore ៙ Be not permitted ៜ Punctuation: commas ,, quotation marks ?, or periods . ៜ Spaces ៙ e.g. ៜ $id, $_name and $query3: valid ៜ $96, $day. and email: invalid ៚ Variable names are case-sensitive. ៙ e.g. $name and $Name refer to different variables. 3
  • 4. Assigning Values to Variables ៚ $var = val; ៙ e.g. assigningValues2Variables.php <?php $language = "PHP"; ?> <h1>Welcome <?php echo $language; ?></h1> ៚ Dynamic variable's name ៙ e.g. dynamicVariableName.php <?php $clone = "real"; // create a value of ${$clone} = echo $real; ?> new variable dynamically $clone "REAL"; // output: REAL at run time from the Is it possible for a variable's name itself to be a variable? ៚ echo(): print the value of a variable 4
  • 5. Destroying Variables ៚ e.g. destroyingVariables.php <?php $apple = "Apple"; echo $apple; // output: Apple // unset() unset($apple); echo $apple; // error: Undefined variable $banana = "Banana"; echo $banana; // // NULL value $banana = NULL; echo $banana; // ?> output: Banana output: (nothing) 5
  • 6. Inspecting Variable Contents ៚ e.g. inspectingVariableContents.php <?php $apple = "Apple"; $yr = 2011; // var_dump() var_dump($apple); var_dump($yr); // // output: string(5) output: int(2011) "Apple" // print_r() print_r($apple); // output: Apple print_r($yr); ?> // output: 2011 6
  • 7. Understanding PHP’s Data Types ៚ Data type is the values assigned to a variable. ៚ Booleans ៙ 1 (true) or 0 (false) ៚ 2 numeric ៙ Floating-point values (a.k.a floats or doubles) are decimal or fractional numbers, ៙ While integers are round numbers. ៚ Non-numeric: String ៙ Be enclosed in single quotes (') or double quotes (") ៚ NULL (a special data type in PHP4) ៙ Represent empty variables; a variable of type NULL is a variable without any data. A NULL value is not equivalent to an empty string "". 7
  • 8. Understanding PHP’s Data Types (cont.) ៚ e.g. hexadecimal_octal_scientificNotation.php <?php $dec echo = 8; // decimal $dec; // output: 8 $oct echo = 010; // octal $oct; // output: 8 $hex echo = 0x5dc; $hex; // // hexadecimal output: 1500 // scientific notation $sn1 $sn2 echo ?> = 6.9e+2; = 6.9e-2; $sn1." ".$sn2; // output: 690 0.069 8
  • 9. Setting and Checking Variable Data Types ៚ e.g. setting_CheckingVariableDataTypes.php <?php $apple = "Apple"; echo gettype($apple); // output: string $yr = 2011; echo gettype($yr); // output: integer $valid = true; echo gettype($valid); // output : boolean echo gettype($banana); // output: NULL variable) (error: Undefined $empty = NULL; echo gettype($empty); // output: NULL ?> 9
  • 10. Setting and Checking Variable Data Types (cont.) ៚ e.g. casting.php <?php $f_speed = $i_speed = // output: 36.9; // floating-point (integer) 36.9 $f_speed; // cast to integer echo $f_speed; // output: 36 echo ?> $i_speed;; 10 Data Type Checking Functions Function Purpose is_bool Test if holding a Boolean value is_numeric Test if holding a numeric value is_int Test if holding an integer value is_float Test if holding a float value is_string Test if holding a string value is_null Test if holding a NULL value is_array Test if being an array is_object Test if being an object
  • 11. Using Constants ៚ define(CONST, val); ៚ Constant names follows the same rules as variable names but not the $ ៚ e.g. usingConstants.php <?php define("APPLE", "Apple"); define("YR", 2011); prefix. // output: Apple 2011 echo ?> APPLE." ".YR; Constants name are usually entirely UPPERCASED. When should we use a variable, and when should we use a constant? 11
  • 12. Manipulating Variables with Operators ៚ Operators are symbols that tell the PHP processor to perform certain actions. ៚ PHP supports more than 50 such operators, ranging from operators for arithmetical operations to operators for logical comparison and bitwise calculations. 12
  • 13. Performing Arithmetic Operations ៚ e.g. arithmeticOperations.php <?php echo 3 + 2; // output: 5 echo 3 - 2; // output: 1 echo 3 * 2; // output: 6 echo 3 / 2; // output: 1.5 echo ?> 3 % 2; // output: 1 Is there any limit on how large a PHP integer value can be? 13 Arithmetic Operators Operator Description + Add - Subtract * Multiply / Divide % Modulus
  • 14. Concatenating Strings ៚ e.g. concatenatingStrings.php <?php $apple = "Apple"; $banana = "Banana"; // use (.) to join strings into 1 $fruits = $apple." and ".$banana; // output: I love apple and ".$fruits."."; banana.. echo ?> "I love 14
  • 15. Comparing Variables ៚ e.g. comparingVariables.php <?php $num = 6; $num2 = 3; $str = "6"; // output: echo ($num // output: echo ($num 0 < 1 > (false) $num2); (true) $num2); // output: echo ($num 0 < (false) $str); // output: echo ($num // output: echo ($num ?> 1 (true) == $str); 0 (false) === $str); 15 Comparison Operators Operator Description == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to === Equal to and of the same type
  • 16. Performing Logical Tests ៚ e.g. performingLogicalTests.php <?php // output: echo (true // output: echo (true // output: 1 (true) && true); 0 (false) && false); 0 (false) echo (false && false); // output: 1 (true) echo (false || true); // output: 0 (false) echo (!true); ?> 16 Logical Operators Operator Description && AND || OR ! NOT
  • 17. Other Useful Operators ៚ e.g. otherUsefulOperators.php <?php $count = 7; $age = 60; $greet = "We"; Increased by 1: ++ Decreased by 1: -- $count -= 2; // output: 5 echo $count; e.g. $count++; // $count = $count + 1; $age /= 5; // output: 12 echo $age; $greet .= "lcome!"; // output: Welcome! echo $greet; ?> 17 Assignment Operators Operator Description += Add, assign -= Subtract, assign *= Multiply, assign /= Divide, assign %= Modulus, assign .= Concatenate, assign
  • 18. Understanding Operator Precedence ៚ Operators at the same level have equal precedence: ៙ ++ ៙ ! ៙ * ៙ + ៙ < ៙ == ៙ && ៙ || ៙ = -- / - <= != % . > >= === !== += -= *= /= .= %= &= |= ^= ៚ Parentheses ( ៚ e.g. ៙ 3 + 2 * ៙ (3 + 2) ): force PHP to evaluate it first 5; // 3 + 10 = 13 * 5; // 5 * 5 = 25 18
  • 19. Handling Form Input ៚ e.g. chooseCar.html <form name="fCar" method="POST" action="getCar.php"> <select name="selType"> <option value="Porsche">Porsche</option> <option value="Ford">Ford</option> </select> Color: <input <input </form> type="text" name="txtColor" /> type="submit" value="get Car" /> action="getCar.php" Reference a PHP script method="POST" Submission via POST GET: method="GET" 19
  • 20. Handling Form Input (cont.) ៚ e.g. getCar.php <?php // get values via $_POST | $_GET $type = $_POST["selType"]; $color = $_POST["txtColor"]; echo $color." ".$type; ?> $_POST[fieldName]; $_POST: a special container variable (array) is used to get a value of a field of a form sent by using the POST method (or $_GET for the GET method). fieldName: the field whose value will be get/assigned to a variable. 20