SlideShare une entreprise Scribd logo
1  sur  53
Télécharger pour lire hors ligne
FooLab


PHP Workshop #1
First Programming Experience
Who are you?                             FooLab

• Have you ever written PHP before?

• Have you ever written computer code before?

• Have you ever seen computer code?

• Ask for the name of your neighbor on each side.


                           2
Anna Filina                                      FooLab

• PHP Quebec - user group, organizer.

• ConFoo - non for profit Web conference, organizer.

• FooLab Inc. - IT consulting, vice-president.

• I write code.

• I train people.

                               3
Programming                                 FooLab
Describing procedures

    Input
                    Find                 Password
  username
                  username               matches?
and password
                                   Yes              No


                                Open           Display error
                             account page        message


                             4
Functions                       FooLab

One step in the whole program


                          pi    3.141592 ...



       26, 58            max        58


       Y-m-d             date   2012-04-26


                           5
Interactive Shell                           FooLab


• We can see result of PHP code as we type it.

• Open your console. Type phpsh

• After each line of code, press enter to execute it.



                              6
Functions                    FooLab


 php> echo pi();

 php> echo max(26,58);

 php> echo max (26, 58);

 php> echo date("Y-m-d");




                         7
Interpreter                    FooLab

• I like like

   php> echo echo;


• I like the word “like”

   php> echo "echo";



                           8
Data Types                                  FooLab

• Integer, can’t confuse with commands or functions:

   php> echo 33;


• String, use quotes:

   php> echo "Programming is cool";


• There are more types, but that’s for later.

                              9
Variables                        FooLab

• "Programming is cool"
• "Design is cool"
• "Video editing is cool"

  php> $hobby = "Design";
  php> echo $hobby;
  php> echo "$hobby is cool";



                            10
FooLab

                                      Design
• Use the $ sign to refer
   to the bin’s name.
                                       hobby
• Use the = sign to put
   content in the bin.
                                 $hobby = "Design"



                            11
FooLab

                                    Design
• No sign is needed to get
   the bin’s content out.
                                     hobby
• A variable is where we
   put a value.
                                  echo $hobby



                             12
Writing Code in Files FooLab


• It’s easier to write multiple lines of code in a file.

• Open your text editor.

• Open the file /var/www/php1/script.php



                                13
FooLab
• Quit the interactive shell by typing:

   php> q

• Now you can run your file using:

   $ php /var/www/php1/script.php

• Repeat the previous command by pressing the up arrow.

• Every time we edit our file, we’ll test the code.
                                14
FooLab

• The file currently contains the following text:

   <?php
   $hobby = "Design";
   echo "$hobby is cool";
   ?>

• The file ends in empty lines. Don’t delete them.


                                15
Movie Price                           FooLab


• Movie costs 12$

• Popcorn costs 8$

• Popcorn can be shared between two people.



                          16
FooLab


• What happens with popcorn when we have an odd
  number of people?

  ceil(3 / 2);




                         17
Procedure                                FooLab

Calculate total movie cost based on number of people


  Set number of      Get number of
      people           popcorns         Popcorns * 8
    (variable)         required



                      Display sum        Tickets * 12



                           18
Practice!                                    FooLab
•   Write a script that, given any number of people,
    calculates the total price for movie and popcorn.

    •   Set number of people (variable)

    •   Get number of popcorns required

    •   Popcorns * 8

    •   Tickets * 12

    •   Display sum
                               19
Answer                           FooLab


<?php
$people = 3;
echo ceil($people / 2) * 8 + $people * 12;
?>




                     20
FooLab


Functions
Understanding Them and Writing Your Own
FooLab

       26, 58         max    58



• Accept parameters

• Perform steps

• Return result

                      22
Create and Call a Function           FooLab

• Wrap code in a function:
   function movie_price($people) {
     $total = ceil($people / 2) * 8 + $people * 12;
     return $total;
   }


• Call function:

   echo movie_price(5);

                             23
What Happened? FooLab

   Number of                        Price was
                   Price came out
 people went in                     displayed

      (5)                 84          echo


            movie_price




                          24
FooLab

Working With Text and
Numbers
Using String and Math Functions
String and Math Functions                  FooLab


• Open the interactive shell: phpsh

   php>   echo   rand(1, 3);
   php>   echo   rand(1, 100);
   php>   echo   strlen("FooLab");
   php>   echo   substr("FooLab", 3);
   php>   echo   substr("FooLab", 3, 1);



                            26
Position zero                            FooLab


• Many programming languages start counting at zero.


                 F      o        o   L      a      b
 advance by:     0      1        2   3      4      5



                            27
Practice!                                    FooLab

• Write a function that calculates a rectangle’s area using
   height and width.

• Write a function that returns a random letter from the
   alphabet. Hint: $letters = “abcdefg...”

  • substr(text, start, length)

  • rand(min, max)

                             28
Answer                                        FooLab


 function area($h, $w) {
   return $h * $w;
 }


 function rand_letter() {
   $letters = "abcdefghijklmnopqrstuvwxyz";
   return substr($letters, rand(0,25), 1);
 }




                             29
FooLab


Conditions
If It’s Cold, Wear a Coat
FooLab



• Expression: produces a value of true or false.

• Execute a process only if the expression is true.




                             31
Writing Conditional
Statements                               FooLab


• Open the script.php file in your text editor.

   $temp = 12;
   if ($temp < 15) {
     echo "Wear a coat";
   }




                           32
FooLab


$temp = 20;
if ($temp < 15) {
  echo "Wear a coat";
}
else {
  echo "It's hot enough";
}




                     33
Mental Exercise   FooLab


 1 < 1

 1 == 1

 1 != 1




            34
Combining Expressions                  FooLab



• Temperature is less than 5 degrees
   and
   wind is greater than 30 km/h




                            35
Logical Operators FooLab

 true && true

 true && false

 true || false

 false || false



                  36
FooLab


Repetition
Lather. Rinse. Repeat.
Vocabulary                      FooLab


• Repetition (to repeat)

• Loop (to loop)

• Iteration (to iterate)



                           38
Writing Loops                                   FooLab

• for (initially ; iterate this time? ; after each iteration)

   for ($i = 1; $i <= 3; $i++) {
     echo $i;
   }


• $i++ is the same as $i = $i + 1


                                39
What Happened? FooLab
$i = 1; $i <= 3; $i++


    $i <= 3     $i <= 3        $i <= 3   $i <= 3



    echo $i     echo $i        echo $i    stop



     $i = 2     $i = 3         $i = 4

                          40
Chorus                            FooLab



 for ($i = 1; $i <= 4; $i++) {
   echo "This song is just six words longn";
 }




                      41
Array                      FooLab
An ordered set of related elements




                  42
Array                      FooLab
An ordered set of related elements




                  43
What Is An Array? FooLab


                         page          page     page
       book
                          0             1        2

                       number         number   "Text"



• You can put books in boxes for “nested” arrays,
   but that’s for another day.
                                 44
Acces Elements By Index            FooLab



$movies = array("Titanic", "Shrek", "Die Hard");
echo $movies[1];




                        45
Iterating Over Arrays FooLab


$movies = array("Titanic", "Shrek", "Die Hard");

foreach ($movies as $movie) {
  echo "I watched $movien";
}




                        46
Getting Index and Value                    FooLab


• In addition to the value, you can also get the index for
   each iteration:

   foreach ($movies as $index => $movie)




                             47
Concatenation                                  FooLab
• Link bits of text together using a dot (.)

   echo "You rolled " . rand(2, 12);


• Useful in a loop

   $sequence = "";
   for ($i = 1; $i <= 10; $i++) {
     $sequence = $sequence . rand(0, 9);
   }
   echo $sequence;
                              48
Practice!                                 FooLab

• Write a function that creates a random 9-character,
   pronouncable password.

  • 3 cyllables, 3 letters each
  • Consonant, vowel, consonant
  • Should produce something like this:
      “hagrokwag”


                            49
Answer                                         FooLab
function rand_vowel() {
  $vowels = "aeiou";
  return substr($vowels, rand(0,4), 1);
}
function rand_consonant() {
  $consonants = "bcdfghjklmnpqrstvwxyz";
  return substr($consonants, rand(0,20), 1);
}
function rand_password() {
  $pass = "";
  for ($i = 1; $i <= 3; $i++ ) {
    $pass = $pass.rand_consonant().rand_vowel().rand_consonant();
  }
  return $pass;
}

                                50
Trivia                                     FooLab

• 6 ^ 21 + 3 ^ 5
   gives over 20 quadrillions combinations

• It will take millions of years for a computer
   to try them all

• And you can pronounce it, making it easy to memorize!


                             51
Next Steps                             FooLab
• Go to phpjunkyard.com

• Download some script

• See how it works

• Play with the code

• Anything you put in /var/www/php1 can be accessed in
   the browser: http://php1.local/
                          52
Resources                                 FooLab



• php.net has a manual and a reference for all functions.

• phpquebec.org is the PHP users group in Montreal.




                            53

Contenu connexe

Tendances

F# and Reactive Programming for iOS
F# and Reactive Programming for iOSF# and Reactive Programming for iOS
F# and Reactive Programming for iOSBrad Pillow
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaLin Yo-An
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlBruce Gray
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in ProgrammingxSawyer
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Parkpointstechgeeks
 
Logic Progamming in Perl
Logic Progamming in PerlLogic Progamming in Perl
Logic Progamming in PerlCurtis Poe
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 
From Python to Scala
From Python to ScalaFrom Python to Scala
From Python to ScalaFFunction inc
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational BiologyAtreyiB
 
Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Yuji Otani
 

Tendances (15)

F# and Reactive Programming for iOS
F# and Reactive Programming for iOSF# and Reactive Programming for iOS
F# and Reactive Programming for iOS
 
Ruby
RubyRuby
Ruby
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line Perl
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 
Elixir
ElixirElixir
Elixir
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Logic Progamming in Perl
Logic Progamming in PerlLogic Progamming in Perl
Logic Progamming in Perl
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
From Python to Scala
From Python to ScalaFrom Python to Scala
From Python to Scala
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7
 

En vedette

Why Learn PHP Programming?
Why Learn PHP Programming?Why Learn PHP Programming?
Why Learn PHP Programming?XtreemHeights
 
Automatic Generation Control
Automatic Generation ControlAutomatic Generation Control
Automatic Generation ControlBirju Besra
 
Intégration #1 : introduction
Intégration #1 : introductionIntégration #1 : introduction
Intégration #1 : introductionJean Michel
 
Using mySQL in PHP
Using mySQL in PHPUsing mySQL in PHP
Using mySQL in PHPMike Crabb
 
Financial intelligent for start ups
Financial intelligent for start upsFinancial intelligent for start ups
Financial intelligent for start upsjubril
 
Presentation & Pitching tips
Presentation & Pitching tipsPresentation & Pitching tips
Presentation & Pitching tipsABrandNewYou
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
How to Use Publicity to Grow Your Startup
How to Use Publicity to Grow Your StartupHow to Use Publicity to Grow Your Startup
How to Use Publicity to Grow Your StartupJoy Schoffler
 
Excel training for beginners
Excel training for beginnersExcel training for beginners
Excel training for beginnersParul Sharan
 
Beating the decline of the Facebook Organic Reach - KRDS singapore
Beating the decline of the Facebook Organic Reach - KRDS singapore Beating the decline of the Facebook Organic Reach - KRDS singapore
Beating the decline of the Facebook Organic Reach - KRDS singapore KRDS
 
How to present your business plan to investors
How to present your business plan to investorsHow to present your business plan to investors
How to present your business plan to investorsThe Hatch
 

En vedette (20)

Why Learn PHP Programming?
Why Learn PHP Programming?Why Learn PHP Programming?
Why Learn PHP Programming?
 
Automatic Generation Control
Automatic Generation ControlAutomatic Generation Control
Automatic Generation Control
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 
Intégration #1 : introduction
Intégration #1 : introductionIntégration #1 : introduction
Intégration #1 : introduction
 
Using mySQL in PHP
Using mySQL in PHPUsing mySQL in PHP
Using mySQL in PHP
 
Fcp lecture 01
Fcp lecture 01Fcp lecture 01
Fcp lecture 01
 
Financial intelligent for start ups
Financial intelligent for start upsFinancial intelligent for start ups
Financial intelligent for start ups
 
Presentation & Pitching tips
Presentation & Pitching tipsPresentation & Pitching tips
Presentation & Pitching tips
 
JQuery-Tutorial
 JQuery-Tutorial JQuery-Tutorial
JQuery-Tutorial
 
Microsoft excel beginner
Microsoft excel beginnerMicrosoft excel beginner
Microsoft excel beginner
 
Intro to php
Intro to phpIntro to php
Intro to php
 
How to Use Publicity to Grow Your Startup
How to Use Publicity to Grow Your StartupHow to Use Publicity to Grow Your Startup
How to Use Publicity to Grow Your Startup
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
Excel training for beginners
Excel training for beginnersExcel training for beginners
Excel training for beginners
 
phpTutorial1
phpTutorial1phpTutorial1
phpTutorial1
 
Beating the decline of the Facebook Organic Reach - KRDS singapore
Beating the decline of the Facebook Organic Reach - KRDS singapore Beating the decline of the Facebook Organic Reach - KRDS singapore
Beating the decline of the Facebook Organic Reach - KRDS singapore
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
How to present your business plan to investors
How to present your business plan to investorsHow to present your business plan to investors
How to present your business plan to investors
 
Comp 107 cep ii
Comp 107 cep iiComp 107 cep ii
Comp 107 cep ii
 
Comp 107chp 1
Comp 107chp 1Comp 107chp 1
Comp 107chp 1
 

Similaire à Intro to PHP for Beginners

Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talkReuven Lerner
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with GoSteven Francia
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbaivibrantuser
 
Geecon 2019 - Taming Code Quality in the Worst Language I Know: Bash
Geecon 2019 - Taming Code Quality  in the Worst Language I Know: BashGeecon 2019 - Taming Code Quality  in the Worst Language I Know: Bash
Geecon 2019 - Taming Code Quality in the Worst Language I Know: BashMichał Kordas
 
TAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith AdamsTAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith AdamsHermes Alves
 
Php(report)
Php(report)Php(report)
Php(report)Yhannah
 
WWX2014 speech : Elliott Stoneham "Tardis go"
WWX2014 speech : Elliott Stoneham "Tardis go"WWX2014 speech : Elliott Stoneham "Tardis go"
WWX2014 speech : Elliott Stoneham "Tardis go"antopensource
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part oneBingfeng Zhao
 
Php Symfony and software-life-cycle
Php Symfony and software-life-cyclePhp Symfony and software-life-cycle
Php Symfony and software-life-cycleSwatantra Kumar
 

Similaire à Intro to PHP for Beginners (20)

Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
Peek at PHP 7
Peek at PHP 7Peek at PHP 7
Peek at PHP 7
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
Geecon 2019 - Taming Code Quality in the Worst Language I Know: Bash
Geecon 2019 - Taming Code Quality  in the Worst Language I Know: BashGeecon 2019 - Taming Code Quality  in the Worst Language I Know: Bash
Geecon 2019 - Taming Code Quality in the Worst Language I Know: Bash
 
TAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith AdamsTAKING PHP SERIOUSLY - Keith Adams
TAKING PHP SERIOUSLY - Keith Adams
 
Php(report)
Php(report)Php(report)
Php(report)
 
PHP
PHPPHP
PHP
 
WWX2014 speech : Elliott Stoneham "Tardis go"
WWX2014 speech : Elliott Stoneham "Tardis go"WWX2014 speech : Elliott Stoneham "Tardis go"
WWX2014 speech : Elliott Stoneham "Tardis go"
 
01 basics
01 basics01 basics
01 basics
 
php basic
php basicphp basic
php basic
 
Rails console
Rails consoleRails console
Rails console
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Welcome to hack
Welcome to hackWelcome to hack
Welcome to hack
 
From code to pattern, part one
From code to pattern, part oneFrom code to pattern, part one
From code to pattern, part one
 
Elixir
ElixirElixir
Elixir
 
Php Symfony and software-life-cycle
Php Symfony and software-life-cyclePhp Symfony and software-life-cycle
Php Symfony and software-life-cycle
 
Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
 
Prersentation
PrersentationPrersentation
Prersentation
 

Plus de mtlgirlgeeks

Mdawson product strategy preso geek girls 12 7-12 sanitized
Mdawson product strategy preso geek girls 12 7-12 sanitizedMdawson product strategy preso geek girls 12 7-12 sanitized
Mdawson product strategy preso geek girls 12 7-12 sanitizedmtlgirlgeeks
 
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...mtlgirlgeeks
 
Punch it Up with HTML and CSS
Punch it Up with HTML and CSSPunch it Up with HTML and CSS
Punch it Up with HTML and CSSmtlgirlgeeks
 
Girl geek-drupal-intro-jan23-2012
Girl geek-drupal-intro-jan23-2012Girl geek-drupal-intro-jan23-2012
Girl geek-drupal-intro-jan23-2012mtlgirlgeeks
 
Montreal Girl Geeks Public Speaking Workshop
Montreal Girl Geeks Public Speaking WorkshopMontreal Girl Geeks Public Speaking Workshop
Montreal Girl Geeks Public Speaking Workshopmtlgirlgeeks
 
Acoustics Unplugged
Acoustics UnpluggedAcoustics Unplugged
Acoustics Unpluggedmtlgirlgeeks
 

Plus de mtlgirlgeeks (7)

Mdawson product strategy preso geek girls 12 7-12 sanitized
Mdawson product strategy preso geek girls 12 7-12 sanitizedMdawson product strategy preso geek girls 12 7-12 sanitized
Mdawson product strategy preso geek girls 12 7-12 sanitized
 
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...
The Artist’s Code – Tech-inspired Design with Taylor Levy (Montreal Girl Geek...
 
Punch it Up with HTML and CSS
Punch it Up with HTML and CSSPunch it Up with HTML and CSS
Punch it Up with HTML and CSS
 
Girl geek-drupal-intro-jan23-2012
Girl geek-drupal-intro-jan23-2012Girl geek-drupal-intro-jan23-2012
Girl geek-drupal-intro-jan23-2012
 
Intro to Drupal
Intro to DrupalIntro to Drupal
Intro to Drupal
 
Montreal Girl Geeks Public Speaking Workshop
Montreal Girl Geeks Public Speaking WorkshopMontreal Girl Geeks Public Speaking Workshop
Montreal Girl Geeks Public Speaking Workshop
 
Acoustics Unplugged
Acoustics UnpluggedAcoustics Unplugged
Acoustics Unplugged
 

Dernier

the Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationthe Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationbrynpueblos04
 
March 2023 Recommendations for newsletter
March 2023 Recommendations for newsletterMarch 2023 Recommendations for newsletter
March 2023 Recommendations for newsletterssuserdfec6a
 
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsColaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDeepika Singh
 
Social Learning Theory presentation.pptx
Social Learning Theory presentation.pptxSocial Learning Theory presentation.pptx
Social Learning Theory presentation.pptxumef01177
 
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDeepika Singh
 
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptx
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptxSIKP311 Sikolohiyang Pilipino - Ginhawa.pptx
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptxStephenMino
 
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...mitaliverma221
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theorydrae5
 
February 2024 Recommendations for newsletter
February 2024 Recommendations for newsletterFebruary 2024 Recommendations for newsletter
February 2024 Recommendations for newsletterssuserdfec6a
 
2023 - Between Philosophy and Practice: Introducing Yoga
2023 - Between Philosophy and Practice: Introducing Yoga2023 - Between Philosophy and Practice: Introducing Yoga
2023 - Between Philosophy and Practice: Introducing YogaRaphaël Semeteys
 
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...Cara Menggugurkan Kandungan 087776558899
 
Emotional Freedom Technique Tapping Points Diagram.pdf
Emotional Freedom Technique Tapping Points Diagram.pdfEmotional Freedom Technique Tapping Points Diagram.pdf
Emotional Freedom Technique Tapping Points Diagram.pdfaprilross605
 
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsGoregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDeepika Singh
 
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdf
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdfExploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdf
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdfMindful Wellness Journey
 

Dernier (15)

Girls in Mahipalpur (delhi) call me [🔝9953056974🔝] escort service 24X7
Girls in Mahipalpur  (delhi) call me [🔝9953056974🔝] escort service 24X7Girls in Mahipalpur  (delhi) call me [🔝9953056974🔝] escort service 24X7
Girls in Mahipalpur (delhi) call me [🔝9953056974🔝] escort service 24X7
 
the Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationthe Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentation
 
March 2023 Recommendations for newsletter
March 2023 Recommendations for newsletterMarch 2023 Recommendations for newsletter
March 2023 Recommendations for newsletter
 
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsColaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Colaba Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
 
Social Learning Theory presentation.pptx
Social Learning Theory presentation.pptxSocial Learning Theory presentation.pptx
Social Learning Theory presentation.pptx
 
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsDadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Dadar West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
 
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptx
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptxSIKP311 Sikolohiyang Pilipino - Ginhawa.pptx
SIKP311 Sikolohiyang Pilipino - Ginhawa.pptx
 
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East G...
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theory
 
February 2024 Recommendations for newsletter
February 2024 Recommendations for newsletterFebruary 2024 Recommendations for newsletter
February 2024 Recommendations for newsletter
 
2023 - Between Philosophy and Practice: Introducing Yoga
2023 - Between Philosophy and Practice: Introducing Yoga2023 - Between Philosophy and Practice: Introducing Yoga
2023 - Between Philosophy and Practice: Introducing Yoga
 
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
 
Emotional Freedom Technique Tapping Points Diagram.pdf
Emotional Freedom Technique Tapping Points Diagram.pdfEmotional Freedom Technique Tapping Points Diagram.pdf
Emotional Freedom Technique Tapping Points Diagram.pdf
 
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot GirlsGoregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
Goregaon West Escorts 🥰 8617370543 Call Girls Offer VIP Hot Girls
 
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdf
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdfExploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdf
Exploring Stoic Philosophy From Ancient Wisdom to Modern Relevance.pdf
 

Intro to PHP for Beginners

  • 1. FooLab PHP Workshop #1 First Programming Experience
  • 2. Who are you? FooLab • Have you ever written PHP before? • Have you ever written computer code before? • Have you ever seen computer code? • Ask for the name of your neighbor on each side. 2
  • 3. Anna Filina FooLab • PHP Quebec - user group, organizer. • ConFoo - non for profit Web conference, organizer. • FooLab Inc. - IT consulting, vice-president. • I write code. • I train people. 3
  • 4. Programming FooLab Describing procedures Input Find Password username username matches? and password Yes No Open Display error account page message 4
  • 5. Functions FooLab One step in the whole program pi 3.141592 ... 26, 58 max 58 Y-m-d date 2012-04-26 5
  • 6. Interactive Shell FooLab • We can see result of PHP code as we type it. • Open your console. Type phpsh • After each line of code, press enter to execute it. 6
  • 7. Functions FooLab php> echo pi(); php> echo max(26,58); php> echo max (26, 58); php> echo date("Y-m-d"); 7
  • 8. Interpreter FooLab • I like like php> echo echo; • I like the word “like” php> echo "echo"; 8
  • 9. Data Types FooLab • Integer, can’t confuse with commands or functions: php> echo 33; • String, use quotes: php> echo "Programming is cool"; • There are more types, but that’s for later. 9
  • 10. Variables FooLab • "Programming is cool" • "Design is cool" • "Video editing is cool" php> $hobby = "Design"; php> echo $hobby; php> echo "$hobby is cool"; 10
  • 11. FooLab Design • Use the $ sign to refer to the bin’s name. hobby • Use the = sign to put content in the bin. $hobby = "Design" 11
  • 12. FooLab Design • No sign is needed to get the bin’s content out. hobby • A variable is where we put a value. echo $hobby 12
  • 13. Writing Code in Files FooLab • It’s easier to write multiple lines of code in a file. • Open your text editor. • Open the file /var/www/php1/script.php 13
  • 14. FooLab • Quit the interactive shell by typing: php> q • Now you can run your file using: $ php /var/www/php1/script.php • Repeat the previous command by pressing the up arrow. • Every time we edit our file, we’ll test the code. 14
  • 15. FooLab • The file currently contains the following text: <?php $hobby = "Design"; echo "$hobby is cool"; ?> • The file ends in empty lines. Don’t delete them. 15
  • 16. Movie Price FooLab • Movie costs 12$ • Popcorn costs 8$ • Popcorn can be shared between two people. 16
  • 17. FooLab • What happens with popcorn when we have an odd number of people? ceil(3 / 2); 17
  • 18. Procedure FooLab Calculate total movie cost based on number of people Set number of Get number of people popcorns Popcorns * 8 (variable) required Display sum Tickets * 12 18
  • 19. Practice! FooLab • Write a script that, given any number of people, calculates the total price for movie and popcorn. • Set number of people (variable) • Get number of popcorns required • Popcorns * 8 • Tickets * 12 • Display sum 19
  • 20. Answer FooLab <?php $people = 3; echo ceil($people / 2) * 8 + $people * 12; ?> 20
  • 22. FooLab 26, 58 max 58 • Accept parameters • Perform steps • Return result 22
  • 23. Create and Call a Function FooLab • Wrap code in a function: function movie_price($people) { $total = ceil($people / 2) * 8 + $people * 12; return $total; } • Call function: echo movie_price(5); 23
  • 24. What Happened? FooLab Number of Price was Price came out people went in displayed (5) 84 echo movie_price 24
  • 25. FooLab Working With Text and Numbers Using String and Math Functions
  • 26. String and Math Functions FooLab • Open the interactive shell: phpsh php> echo rand(1, 3); php> echo rand(1, 100); php> echo strlen("FooLab"); php> echo substr("FooLab", 3); php> echo substr("FooLab", 3, 1); 26
  • 27. Position zero FooLab • Many programming languages start counting at zero. F o o L a b advance by: 0 1 2 3 4 5 27
  • 28. Practice! FooLab • Write a function that calculates a rectangle’s area using height and width. • Write a function that returns a random letter from the alphabet. Hint: $letters = “abcdefg...” • substr(text, start, length) • rand(min, max) 28
  • 29. Answer FooLab function area($h, $w) { return $h * $w; } function rand_letter() { $letters = "abcdefghijklmnopqrstuvwxyz"; return substr($letters, rand(0,25), 1); } 29
  • 31. FooLab • Expression: produces a value of true or false. • Execute a process only if the expression is true. 31
  • 32. Writing Conditional Statements FooLab • Open the script.php file in your text editor. $temp = 12; if ($temp < 15) { echo "Wear a coat"; } 32
  • 33. FooLab $temp = 20; if ($temp < 15) { echo "Wear a coat"; } else { echo "It's hot enough"; } 33
  • 34. Mental Exercise FooLab 1 < 1 1 == 1 1 != 1 34
  • 35. Combining Expressions FooLab • Temperature is less than 5 degrees and wind is greater than 30 km/h 35
  • 36. Logical Operators FooLab true && true true && false true || false false || false 36
  • 38. Vocabulary FooLab • Repetition (to repeat) • Loop (to loop) • Iteration (to iterate) 38
  • 39. Writing Loops FooLab • for (initially ; iterate this time? ; after each iteration) for ($i = 1; $i <= 3; $i++) { echo $i; } • $i++ is the same as $i = $i + 1 39
  • 40. What Happened? FooLab $i = 1; $i <= 3; $i++ $i <= 3 $i <= 3 $i <= 3 $i <= 3 echo $i echo $i echo $i stop $i = 2 $i = 3 $i = 4 40
  • 41. Chorus FooLab for ($i = 1; $i <= 4; $i++) { echo "This song is just six words longn"; } 41
  • 42. Array FooLab An ordered set of related elements 42
  • 43. Array FooLab An ordered set of related elements 43
  • 44. What Is An Array? FooLab page page page book 0 1 2 number number "Text" • You can put books in boxes for “nested” arrays, but that’s for another day. 44
  • 45. Acces Elements By Index FooLab $movies = array("Titanic", "Shrek", "Die Hard"); echo $movies[1]; 45
  • 46. Iterating Over Arrays FooLab $movies = array("Titanic", "Shrek", "Die Hard"); foreach ($movies as $movie) { echo "I watched $movien"; } 46
  • 47. Getting Index and Value FooLab • In addition to the value, you can also get the index for each iteration: foreach ($movies as $index => $movie) 47
  • 48. Concatenation FooLab • Link bits of text together using a dot (.) echo "You rolled " . rand(2, 12); • Useful in a loop $sequence = ""; for ($i = 1; $i <= 10; $i++) { $sequence = $sequence . rand(0, 9); } echo $sequence; 48
  • 49. Practice! FooLab • Write a function that creates a random 9-character, pronouncable password. • 3 cyllables, 3 letters each • Consonant, vowel, consonant • Should produce something like this: “hagrokwag” 49
  • 50. Answer FooLab function rand_vowel() { $vowels = "aeiou"; return substr($vowels, rand(0,4), 1); } function rand_consonant() { $consonants = "bcdfghjklmnpqrstvwxyz"; return substr($consonants, rand(0,20), 1); } function rand_password() { $pass = ""; for ($i = 1; $i <= 3; $i++ ) { $pass = $pass.rand_consonant().rand_vowel().rand_consonant(); } return $pass; } 50
  • 51. Trivia FooLab • 6 ^ 21 + 3 ^ 5 gives over 20 quadrillions combinations • It will take millions of years for a computer to try them all • And you can pronounce it, making it easy to memorize! 51
  • 52. Next Steps FooLab • Go to phpjunkyard.com • Download some script • See how it works • Play with the code • Anything you put in /var/www/php1 can be accessed in the browser: http://php1.local/ 52
  • 53. Resources FooLab • php.net has a manual and a reference for all functions. • phpquebec.org is the PHP users group in Montreal. 53