SlideShare a Scribd company logo
1 of 18
Download to read offline
PHP Basics

Nelson Ochieng
Instruction Separation
•   PHP requires instructions to be terminated with a semicolon at the end of
    each statement.
•   The closing tag of a block of PHP code automatically implies a semicolon;

<?php
    echo 'This is a test';
?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';
Comments
<?php
    echo 'This is a test'; //       This is a one-line c++ style comment


     /* This is a multi line comment
        yet another line of comment */

     echo 'This is yet another test';
     echo 'One Final Test'; # This is a one-line   shell-style comment

?>
Types
•   Some types that PHP supports.
•   Four scalar types:
     –   boolean
     –   integer
     –   float (floating-point number, aka double)
     –   string
•   Two compound types:
     –   array
     –   object
•   And finally three special types:
     –   resource
     –   NULL
<?php
$a_bool = TRUE;   // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12;     // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}
// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}
?>
Booleans
•   A boolean expression expresses a truth value. Can be TRUE or FALSE
<?php
$foo = True; // assign the value TRUE to $foo
?>
<?php
// == is an operator which tests
// equality and returns a boolean
if ($action == "show_version") {
    echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo "<hr>n";
}

// ...because this can be used with exactly the same meaning:
if ($show_separators) {
    echo "<hr>n";
}
Integers
•   An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
•   Integers can be specified in decimal (base 10), hexadecimal (base 16), octal
    (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).
•   To use octal notation, precede the number with a 0 (zero). To use
    hexadecimal notation precede the number with 0x. To use binary notation
    precede the number with 0b.
<?php
$a = 1234;       // decimal number
$a = -123;       // a negative number
$a = 0123;       // octal number (equivalent to 83
   decimal)
$a = 0x1A;       // hexadecimal number (equivalent to 26
   decimal)
?>
Strings
•   A string is series of characters, where a character is the same as a byte.
•   A string literal can be specified in four different ways:
     –   single quoted
     –   double quoted
     –   heredoc syntax
     –   nowdoc syntax (since PHP 5.3.0)
Single Quoted
<?php
   echo 'this is a simple string';

   echo 'You can also have embedded newlines in
   strings this way as it is
   okay to do';

   // Outputs: Arnold once said: "I'll be back"
   echo 'Arnold once said: "I'll be back"';

   // Outputs: You deleted C:*.*?
   echo 'You deleted C:*.*?';

   // Outputs: You deleted C:*.*?
   echo 'You deleted C:*.*?';

   // Outputs: This will not expand: n a newline
   echo 'This will not expand: n a newline';

   // Outputs: Variables do not $expand $either
   echo 'Variables do not $expand $either';
   ?>
Double Quoted
• The most important feature of double-quoted strings is the fact that variable
   names will be expanded.
Heredoc
• A third way to delimit strings is the heredoc syntax: <<<. After this operator,
   an identifier is provided, then a newline. The string itself follows, and then
   the same identifier again to close the quotation.
• The closing identifier must begin in the first column of the line. Also, the
   identifier must follow the same naming rules as any other label in PHP: it
   must contain only alphanumeric characters and underscores, and must start
   with a non-digit character or underscore.
Nowdoc
• A nowdoc is identified with the same <<< sequence used for heredocs, but
   the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All
   the rules for heredoc identifiers also apply to nowdoc identifiers, especially
   those regarding the appearance of the closing identifier.
Arrays
•   An array in PHP is actually an ordered map.
•   A map is a type that associates values to keys.
•   This type is optimized for several different uses:
     –   Array
     –    list (vector)
     –   hash table (an implementation of a map)
     –   Dictionary
     –   Collection
     –   Stack
     –   Queue
     •    As array values can be other arrays, trees and multidimensional arrays
         are also possible.
Specifying an Array
•   An array can be created using the array() language construct.
•   It takes any number of comma-separated key => value pairs as arguments.

array(
    key => value,
    key2 => value2,
    key3 => value3,
    ...
)
Specifying an Array
•   As of PHP 5.4 you can also use the short array syntax, which replaces
    array() with [].
<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);
// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>
•   The key can either be an integer or a string. The value can be of any type.
Accessing array elements with square
               bracket syntax
•   Array elements can be accessed using the array[key] syntax.
<?php
  $array = array(
      "foo" => "bar",
      42     => 24,
      "multi" => array(
           "dimensional" => array(
                "array" => "foo"
           )
      )
  );
    var_dump($array["foo"]);
    var_dump($array[42]);
    var_dump($array["multi"]["dimensional"]["array"]);
    ?>
Creating/modifying with square bracket
                syntax
•   An existing array can be modified by explicitly setting values in it.
•   This is done by assigning values to the array, specifying the key in brackets.
    The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
•   To change a certain value, assign a new value to that element using its key.
•   To remove a key/value pair, call the unset() function on it.
Objects
•   Object Initialization
     –   To create a new object, use the new statement to instantiate a class:
<?php
  class foo
  {
      function do_foo()
      {
          echo "Doing foo."; 
      }
  }

    $bar = new foo;
    $bar->do_foo();
    ?> 
Resources
•   A resource is a special variable, holding a reference to an external resource.
    Resources are created and used by special functions
Null
•   The special NULL value represents a variable with no value.

More Related Content

What's hot (19)

Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Antlr V3
Antlr V3Antlr V3
Antlr V3
 
php string part 4
php string part 4php string part 4
php string part 4
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 

Viewers also liked

Php tutorial
Php tutorialPhp tutorial
Php tutorialNiit
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?Nick Belhomme
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6Wim Godden
 
Subsidio i.1 demanda actual
Subsidio i.1 demanda actualSubsidio i.1 demanda actual
Subsidio i.1 demanda actualUpaep Online
 
Enquête Doctipharma : Les français et la vente de médicaments sur internet
Enquête Doctipharma : Les français et la vente de médicaments sur internet Enquête Doctipharma : Les français et la vente de médicaments sur internet
Enquête Doctipharma : Les français et la vente de médicaments sur internet Doctipharma
 
AOA - Annual OMEL Conference Encourages Osteopathic Discourse
AOA - Annual OMEL Conference Encourages Osteopathic Discourse AOA - Annual OMEL Conference Encourages Osteopathic Discourse
AOA - Annual OMEL Conference Encourages Osteopathic Discourse Dr. Michael Thomas (Neurosurgeon)
 
Tudatos márkaépítés
Tudatos márkaépítésTudatos márkaépítés
Tudatos márkaépítésGabor Papp
 
Estrategias de comunicación para el ciberactivismo
Estrategias de comunicación para el ciberactivismoEstrategias de comunicación para el ciberactivismo
Estrategias de comunicación para el ciberactivismoFreire Juan
 
الإرشاد التربوي والنفسي في المؤسسات التعليمية
الإرشاد التربوي والنفسي في المؤسسات التعليميةالإرشاد التربوي والنفسي في المؤسسات التعليمية
الإرشاد التربوي والنفسي في المؤسسات التعليميةkhalid mechkouri
 
Homoeopathic Home Prescribing Class 18th October 2014
Homoeopathic Home Prescribing Class 18th October 2014Homoeopathic Home Prescribing Class 18th October 2014
Homoeopathic Home Prescribing Class 18th October 2014Owen Homoeopathics
 
JavaScript Craftsmanship: Why JavaScript is Worthy of TDD
JavaScript Craftsmanship: Why JavaScript is Worthy of TDDJavaScript Craftsmanship: Why JavaScript is Worthy of TDD
JavaScript Craftsmanship: Why JavaScript is Worthy of TDDsearls
 
Call me VL-11 28.11.2012 Ole Kassow
Call me VL-11 28.11.2012 Ole KassowCall me VL-11 28.11.2012 Ole Kassow
Call me VL-11 28.11.2012 Ole KassowOle Kassow
 
Virtualni svet Second Life
Virtualni svet Second LifeVirtualni svet Second Life
Virtualni svet Second LifeAlja Isakovic
 
Design persuasivo: alcuni esempi
Design persuasivo: alcuni esempiDesign persuasivo: alcuni esempi
Design persuasivo: alcuni esempiAlberto Mucignat
 
Почему не работают корпоративные социальные сети?
Почему не работают корпоративные социальные сети?Почему не работают корпоративные социальные сети?
Почему не работают корпоративные социальные сети?Anna Nesmeeva
 
урок знам и мога
урок знам и могаурок знам и мога
урок знам и могаChavdara Veleva
 

Viewers also liked (20)

Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
 
Php
PhpPhp
Php
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Subsidio i.1 demanda actual
Subsidio i.1 demanda actualSubsidio i.1 demanda actual
Subsidio i.1 demanda actual
 
Enquête Doctipharma : Les français et la vente de médicaments sur internet
Enquête Doctipharma : Les français et la vente de médicaments sur internet Enquête Doctipharma : Les français et la vente de médicaments sur internet
Enquête Doctipharma : Les français et la vente de médicaments sur internet
 
AOA - Annual OMEL Conference Encourages Osteopathic Discourse
AOA - Annual OMEL Conference Encourages Osteopathic Discourse AOA - Annual OMEL Conference Encourages Osteopathic Discourse
AOA - Annual OMEL Conference Encourages Osteopathic Discourse
 
Tudatos márkaépítés
Tudatos márkaépítésTudatos márkaépítés
Tudatos márkaépítés
 
Estrategias de comunicación para el ciberactivismo
Estrategias de comunicación para el ciberactivismoEstrategias de comunicación para el ciberactivismo
Estrategias de comunicación para el ciberactivismo
 
الإرشاد التربوي والنفسي في المؤسسات التعليمية
الإرشاد التربوي والنفسي في المؤسسات التعليميةالإرشاد التربوي والنفسي في المؤسسات التعليمية
الإرشاد التربوي والنفسي في المؤسسات التعليمية
 
Homoeopathic Home Prescribing Class 18th October 2014
Homoeopathic Home Prescribing Class 18th October 2014Homoeopathic Home Prescribing Class 18th October 2014
Homoeopathic Home Prescribing Class 18th October 2014
 
מחדד 05.03
מחדד 05.03מחדד 05.03
מחדד 05.03
 
JavaScript Craftsmanship: Why JavaScript is Worthy of TDD
JavaScript Craftsmanship: Why JavaScript is Worthy of TDDJavaScript Craftsmanship: Why JavaScript is Worthy of TDD
JavaScript Craftsmanship: Why JavaScript is Worthy of TDD
 
Call me VL-11 28.11.2012 Ole Kassow
Call me VL-11 28.11.2012 Ole KassowCall me VL-11 28.11.2012 Ole Kassow
Call me VL-11 28.11.2012 Ole Kassow
 
Virtualni svet Second Life
Virtualni svet Second LifeVirtualni svet Second Life
Virtualni svet Second Life
 
Design persuasivo: alcuni esempi
Design persuasivo: alcuni esempiDesign persuasivo: alcuni esempi
Design persuasivo: alcuni esempi
 
Почему не работают корпоративные социальные сети?
Почему не работают корпоративные социальные сети?Почему не работают корпоративные социальные сети?
Почему не работают корпоративные социальные сети?
 
islam & art
islam & artislam & art
islam & art
 
урок знам и мога
урок знам и могаурок знам и мога
урок знам и мога
 

Similar to Php basics

Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Michelangelo van Dam
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfAAFREEN SHAIKH
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl courseMarc Logghe
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1Rakesh Mukundan
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 

Similar to Php basics (20)

Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
 
php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Php1
Php1Php1
Php1
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 

Recently uploaded

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 

Recently uploaded (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 

Php basics

  • 2. Instruction Separation • PHP requires instructions to be terminated with a semicolon at the end of each statement. • The closing tag of a block of PHP code automatically implies a semicolon; <?php echo 'This is a test'; ?> <?php echo 'This is a test' ?> <?php echo 'We omitted the last closing tag';
  • 3. Comments <?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shell-style comment ?>
  • 4. Types • Some types that PHP supports. • Four scalar types: – boolean – integer – float (floating-point number, aka double) – string • Two compound types: – array – object • And finally three special types: – resource – NULL
  • 5. <?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $a_bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool"; } ?>
  • 6. Booleans • A boolean expression expresses a truth value. Can be TRUE or FALSE <?php $foo = True; // assign the value TRUE to $foo ?> <?php // == is an operator which tests // equality and returns a boolean if ($action == "show_version") { echo "The version is 1.23"; } // this is not necessary... if ($show_separators == TRUE) { echo "<hr>n"; } // ...because this can be used with exactly the same meaning: if ($show_separators) { echo "<hr>n"; }
  • 7. Integers • An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. • Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). • To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b. <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) ?>
  • 8. Strings • A string is series of characters, where a character is the same as a byte. • A string literal can be specified in four different ways: – single quoted – double quoted – heredoc syntax – nowdoc syntax (since PHP 5.3.0)
  • 9. Single Quoted <?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I'll be back"'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: This will not expand: n a newline echo 'This will not expand: n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?>
  • 10. Double Quoted • The most important feature of double-quoted strings is the fact that variable names will be expanded. Heredoc • A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. • The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. Nowdoc • A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
  • 11. Arrays • An array in PHP is actually an ordered map. • A map is a type that associates values to keys. • This type is optimized for several different uses: – Array – list (vector) – hash table (an implementation of a map) – Dictionary – Collection – Stack – Queue • As array values can be other arrays, trees and multidimensional arrays are also possible.
  • 12. Specifying an Array • An array can be created using the array() language construct. • It takes any number of comma-separated key => value pairs as arguments. array( key => value, key2 => value2, key3 => value3, ... )
  • 13. Specifying an Array • As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. <?php $array = array( "foo" => "bar", "bar" => "foo", ); // as of PHP 5.4 $array = [ "foo" => "bar", "bar" => "foo", ]; ?> • The key can either be an integer or a string. The value can be of any type.
  • 14. Accessing array elements with square bracket syntax • Array elements can be accessed using the array[key] syntax. <?php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?>
  • 15. Creating/modifying with square bracket syntax • An existing array can be modified by explicitly setting values in it. • This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type • To change a certain value, assign a new value to that element using its key. • To remove a key/value pair, call the unset() function on it.
  • 16. Objects • Object Initialization – To create a new object, use the new statement to instantiate a class: <?php class foo {     function do_foo()     {         echo "Doing foo.";      } } $bar = new foo; $bar->do_foo(); ?> 
  • 17. Resources • A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions
  • 18. Null • The special NULL value represents a variable with no value.

Editor's Notes

  1. You do not need to have a semicolon terminating the last line of a PHP block. The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
  2. The &quot;one-line&quot; comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?&gt; or # ... ?&gt; WILL be printed: ?&gt; breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. &lt;h1&gt;This is an &lt;?php # echo &apos;simple&apos;;?&gt; example&lt;/h1&gt; &lt;p&gt;The header above will say &apos;This is an example&apos;.&lt;/p&gt; EXERCISE when the comment string contains &apos;?&gt;&apos;, you should be careful. e.g. output code 1= code 2 is different with code 3 1. with // &lt;?php // echo &apos;&lt;?php ?&gt;&apos;; ?&gt; 2. with # &lt;?php // echo &apos;&lt;?php ?&gt;&apos;; ?&gt; 3. with /* */ &lt;?php /* echo &apos;&lt;?php ?&gt;&apos;;*/ ?&gt; The following code will cause a parse error! the ?&gt; in //?&gt; is not treated as commented text, this is a result of having to handle code on one line such as &lt;?php echo &apos;something&apos;; //comment ?&gt; &lt;?php if(1==1) { //?&gt; } ?&gt;
  3. The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used. To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:
  4. To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.
  5. Typically, the result of an operator which returns a boolean value is passed on to a control structure.
  6. The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Example #3 Integer overflow on a 32-bit system &lt;?php $large_number = 2147483647; var_dump($large_number); // int(2147483647) $large_number = 2147483648; var_dump($large_number); // float(2147483648) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // float(50000000000) ?&gt; Example #4 Integer overflow on a 64-bit system &lt;?php $large_number = 9223372036854775807; var_dump($large_number); // int(9223372036854775807) $large_number = 9223372036854775808; var_dump($large_number); // float(9.2233720368548E+18) $million = 1000000; $large_number = 50000000000000 * $million; var_dump($large_number); // float(5.0E+19) ?&gt; EXERCISE There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding. &lt;?php var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ?&gt;
  7. &lt;?php $str = &lt;&lt;&lt;EOD Example of string spanning multiple lines using heredoc syntax. EOD; &lt;?php $str = &lt;&lt;&lt;&apos;EOD&apos; Example of string spanning multiple lines using nowdoc syntax. EOD;
  8. EXERCISE If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. Example #2 Type Casting and Overwriting example &lt;?php $array = array( 1 =&gt; &quot;a&quot;, &quot;1&quot; =&gt; &quot;b&quot;, 1.5 =&gt; &quot;c&quot;, true =&gt; &quot;d&quot;, ); var_dump($array); ?&gt; The above example will output: array(1) { [1]=&gt; string(1) &quot;d&quot; } As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value &quot;d&quot; is the only one left over. PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. Example #3 Mixed integer and string keys &lt;?php $array = array( &quot;foo&quot; =&gt; &quot;bar&quot;, &quot;bar&quot; =&gt; &quot;foo&quot;, 100 =&gt; -100, -100 =&gt; 100, ); var_dump($array); ?&gt; The above example will output: array(4) { [&quot;foo&quot;]=&gt; string(3) &quot;bar&quot; [&quot;bar&quot;]=&gt; string(3) &quot;foo&quot; [100]=&gt; int(-100) [-100]=&gt; int(100) } The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key. Example #4 Indexed arrays without key &lt;?php $array = array(&quot;foo&quot;, &quot;bar&quot;, &quot;hallo&quot;, &quot;world&quot;); var_dump($array); ?&gt; The above example will output: array(4) { [0]=&gt; string(3) &quot;foo&quot; [1]=&gt; string(3) &quot;bar&quot; [2]=&gt; string(5) &quot;hallo&quot; [3]=&gt; string(5) &quot;world&quot; } It is possible to specify the key only for some elements and leave it out for others: Example #5 Keys not on all elements &lt;?php $array = array( &quot;a&quot;, &quot;b&quot;, 6 =&gt; &quot;c&quot;, &quot;d&quot;, ); var_dump($array); ?&gt; The above example will output: array(4) { [0]=&gt; string(1) &quot;a&quot; [1]=&gt; string(1) &quot;b&quot; [6]=&gt; string(1) &quot;c&quot; [7]=&gt; string(1) &quot;d&quot; } As you can see the last value &quot;d&quot; was assigned the key 7. This is because the largest integer key before that was 6. Accessing array elements with square bracket syntax Array elements can be accessed using the array[key] syntax. Example #6 Accessing array elements &lt;?php $array = array( &quot;foo&quot; =&gt; &quot;bar&quot;, 42 =&gt; 24, &quot;multi&quot; =&gt; array( &quot;dimensional&quot; =&gt; array( &quot;array&quot; =&gt; &quot;foo&quot; ) ) ); var_dump($array[&quot;foo&quot;]); var_dump($array[42]); var_dump($array[&quot;multi&quot;][&quot;dimensional&quot;][&quot;array&quot;]); ?&gt; The above example will output: string(3) &quot;bar&quot; int(24) string(3) &quot;foo&quot; Creating/modifying with square bracket syntax An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type If $arr doesn&apos;t exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. &lt;?php $arr = array(5 =&gt; 1, 12 =&gt; 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr[&quot;x&quot;] = 42; // This adds a new element to // the array with key &quot;x&quot; unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?&gt; Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero). Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: &lt;?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i =&gt; $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?&gt; The above example will output: Array ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 [3] =&gt; 4 [4] =&gt; 5 ) Array ( ) Array ( [5] =&gt; 6 ) Array ( [0] =&gt; 6 [1] =&gt; 7 )
  9. Output string(3) &quot;bar&quot; int(24) string(3) &quot;foo“ Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).
  10. &lt;?php $arr = array(5 =&gt; 1, 12 =&gt; 2); $arr[] = 56;    // This is the same as $arr[13] = 56;                 // at this point of the script $arr[&quot;x&quot;] = 42; // This adds a new element to                 // the array with key &quot;x&quot;                  unset($arr[5]); // This removes the element from the array unset($arr);    // This deletes the whole array ?&gt;