SlideShare a Scribd company logo
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

More Related Content

PDF
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
PDF
Go Java, Go!
PPT
Ruby For Java Programmers
KEY
Source Filters in Perl 2010
PDF
Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...
PDF
Power of Puppet 4
PDF
Drupal 8: A story of growing up and getting off the island
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Go Java, Go!
Ruby For Java Programmers
Source Filters in Perl 2010
Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...
Power of Puppet 4
Drupal 8: A story of growing up and getting off the island

What's hot (14)

PDF
F# and Reactive Programming for iOS
KEY
PDF
Perl.Hacks.On.Vim Perlchina
PDF
Yapc::NA::2009 - Command Line Perl
ODP
Red Flags in Programming
PPTX
PPT
Python - Getting to the Essence - Points.com - Dave Park
PDF
Scala in Practice
PDF
Ruby Gotchas
PDF
Logic Progamming in Perl
PDF
PHP 8.1 - What's new and changed
PDF
From Python to Scala
PPT
Programming in Computational Biology
PPTX
Why choose Hack/HHVM over PHP7
F# and Reactive Programming for iOS
Perl.Hacks.On.Vim Perlchina
Yapc::NA::2009 - Command Line Perl
Red Flags in Programming
Python - Getting to the Essence - Points.com - Dave Park
Scala in Practice
Ruby Gotchas
Logic Progamming in Perl
PHP 8.1 - What's new and changed
From Python to Scala
Programming in Computational Biology
Why choose Hack/HHVM over PHP7
Ad

Viewers also liked (20)

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

Similar to Intro to PHP for Beginners (20)

PDF
Zend Certification Preparation Tutorial
PPT
Php mysql
PPT
slidesharenew1
PPT
My cool new Slideshow!
PDF
Lecture 22
PDF
Cfphp Zce 01 Basics
PPTX
web essentials - simple message flow and loo.pptx
PDF
Lecture19-20
PDF
Lecture19-20
PPTX
PHP PPT FILE
PPT
7.1.intro perl
PDF
Ilucbe python v1.2
PPT
Basic perl programming
PPTX
PPT
Perl Intro 3 Datalog Parsing
PPT
CPAP.com Introduction To Coding: Part 2
PPT
Php introduction
PDF
Phpbasics
PDF
Perl intro
PDF
Zend Certification Preparation Tutorial
Php mysql
slidesharenew1
My cool new Slideshow!
Lecture 22
Cfphp Zce 01 Basics
web essentials - simple message flow and loo.pptx
Lecture19-20
Lecture19-20
PHP PPT FILE
7.1.intro perl
Ilucbe python v1.2
Basic perl programming
Perl Intro 3 Datalog Parsing
CPAP.com Introduction To Coding: Part 2
Php introduction
Phpbasics
Perl intro

More from mtlgirlgeeks (7)

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

Recently uploaded (20)

PPTX
Pradeep Kumar Roll no.30 Paper I.pptx....
PPTX
Chapter-7-The-Spiritual-Self-.pptx-First
PPTX
Emotional Intelligence- Importance and Applicability
PPTX
PERDEV-LESSON-3 DEVELOPMENTMENTAL STAGES.pptx
PDF
The Zeigarnik Effect by Meenakshi Khakat.pdf
PPTX
Identity Development in Adolescence.pptx
PPTX
show1- motivational ispiring positive thinking
PPTX
Learn how to use Portable Grinders Safely
PPTX
diasspresentationndkcnskndncelklkfndc.pptx
PPTX
Presentation on interview preparation.pt
PDF
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
PPTX
Learn how to prevent Workplace Incidents?
PPTX
Travel mania in india needs to change the world
PDF
Attachment Theory What Childhood Says About Your Relationships.pdf
PPTX
SELF ASSESSMENT -SNAPSHOT.pptx an index of yourself by Dr NIKITA SHARMA
PDF
⚡ Prepping for grid failure_ 6 Must-Haves to Survive Blackout!.pdf
PDF
Top 10 Visionary Entrepreneurs to Watch in 2025
PPTX
UNIVERSAL HUMAN VALUES for NEP student .pptx
PPTX
How to Deal with Imposter Syndrome for Personality Development?
PPTX
cấu trúc sử dụng mẫu Cause - Effects.pptx
Pradeep Kumar Roll no.30 Paper I.pptx....
Chapter-7-The-Spiritual-Self-.pptx-First
Emotional Intelligence- Importance and Applicability
PERDEV-LESSON-3 DEVELOPMENTMENTAL STAGES.pptx
The Zeigarnik Effect by Meenakshi Khakat.pdf
Identity Development in Adolescence.pptx
show1- motivational ispiring positive thinking
Learn how to use Portable Grinders Safely
diasspresentationndkcnskndncelklkfndc.pptx
Presentation on interview preparation.pt
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
Learn how to prevent Workplace Incidents?
Travel mania in india needs to change the world
Attachment Theory What Childhood Says About Your Relationships.pdf
SELF ASSESSMENT -SNAPSHOT.pptx an index of yourself by Dr NIKITA SHARMA
⚡ Prepping for grid failure_ 6 Must-Haves to Survive Blackout!.pdf
Top 10 Visionary Entrepreneurs to Watch in 2025
UNIVERSAL HUMAN VALUES for NEP student .pptx
How to Deal with Imposter Syndrome for Personality Development?
cấu trúc sử dụng mẫu Cause - Effects.pptx

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