FooLab
PHP Workshop #1First Programming Experience
FooLabWho are you?
• 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
FooLabAnna Filina
3
• PHP Quebec - user group, organizer.
• ConFoo - non for profit Web conference, organizer.
• FooLab Inc. - IT consulting, vice-president.
• I write code.
• I train people.
FooLabProgramming
4
Input username
and password
Find username
Password matches?
Open account page
Display error message
Yes No
Describing procedures
FooLabFunctions
5
pi 3.141592 ...
26, 58 max 58
Y-m-d date 2012-04-26
One step in the whole program
FooLabInteractive Shell
6
• 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.
FooLabFunctions
7
php> echo pi();
php> echo max(26,58);
php> echo max (26, 58);
php> echo date("Y-m-d");
FooLabInterpreter
8
• I like like
php> echo echo;
• I like the word “like”
php> echo "echo";
FooLabData Types
• 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
FooLabVariables
• "Programming is cool"
• "Design is cool"
• "Video editing is cool"
php> $hobby = "Design";php> echo $hobby;php> echo "$hobby is cool";
10
FooLab
11
hobby
Design• Use the $ sign to refer
to the bin’s name.
• Use the = sign to put content in the bin.
$hobby = "Design"
FooLab
12
hobby
Design• No sign is needed to get
the bin’s content out.
• A variable is where we put a value.
echo $hobby
FooLabWriting Code in Files
13
• It’s easier to write multiple lines of code in a file.
• Open your text editor.
• Open the file /var/www/php1/script.php
FooLab
14
• 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.
FooLab
15
• The file currently contains the following text:
<?php$hobby = "Design";echo "$hobby is cool";?>
• The file ends in empty lines. Don’t delete them.
FooLabMovie Price
16
• Movie costs 12$
• Popcorn costs 8$
• Popcorn can be shared between two people.
FooLab
17
• What happens with popcorn when we have an odd number of people?
ceil(3 / 2);
FooLabProcedure
18
Set number of people
(variable)
Get number of popcorns required
Popcorns * 8
Tickets * 12Display sum
Calculate total movie cost based on number of people
FooLabPractice!
• 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
FooLabAnswer
20
<?php$people = 3;echo ceil($people / 2) * 8 + $people * 12;?>
FooLab
FunctionsUnderstanding Them and Writing Your Own
FooLab
22
• Accept parameters
• Perform steps
• Return result
26, 58 max 58
FooLabCreate and Call a Function
23
• Wrap code in a function:
function movie_price($people) { $total = ceil($people / 2) * 8 + $people * 12; return $total;}
• Call function:
echo movie_price(5);
FooLabWhat Happened?
24
Number of people went in
movie_price
Price came outPrice was displayed
(5) echo84
FooLab
Working With Text and NumbersUsing String and Math Functions
FooLabString and Math Functions
26
• 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);
FooLabPosition zero
27
• Many programming languages start counting at zero.
F o o L a b0advance by: 1 2 3 4 5
FooLabPractice!
• 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
FooLabAnswer
function area($h, $w) { return $h * $w;}
function rand_letter() { $letters = "abcdefghijklmnopqrstuvwxyz"; return substr($letters, rand(0,25), 1);}
29
FooLab
ConditionsIf 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
FooLabWriting Conditional Statements
32
• Open the script.php file in your text editor.
$temp = 12;if ($temp < 15) { echo "Wear a coat";}
FooLab
33
$temp = 20;if ($temp < 15) { echo "Wear a coat";}else { echo "It's hot enough";}
FooLabMental Exercise
1 < 1
1 == 1
1 != 1
34
FooLab
• Temperature is less than 5 degreesandwind is greater than 30 km/h
35
Combining Expressions
FooLab
true && true
true && false
true || false
false || false
36
Logical Operators
FooLab
RepetitionLather. Rinse. Repeat.
FooLabVocabulary
• Repetition (to repeat)
• Loop (to loop)
• Iteration (to iterate)
38
FooLabWriting Loops
39
• for (initially ; iterate this time? ; after each iteration)
for ($i = 1; $i <= 3; $i++) { echo $i;}
• $i++ is the same as $i = $i + 1
FooLabWhat Happened?
40
$i <= 3
echo $i
$i = 1; $i <= 3; $i++
$i = 2
$i <= 3
echo $i
$i = 3
$i <= 3
echo $i
$i = 4
$i <= 3
stop
FooLabChorus
41
for ($i = 1; $i <= 4; $i++) { echo "This song is just six words long\n";}
FooLabArray
42
An ordered set of related elements
FooLabArray
43
An ordered set of related elements
FooLabWhat Is An Array?
44
book page0
page1
page2
number number "Text"
• You can put books in boxes for “nested” arrays,but that’s for another day.
FooLabAcces Elements By Index
45
$movies = array("Titanic", "Shrek", "Die Hard");echo $movies[1];
FooLabIterating Over Arrays
46
$movies = array("Titanic", "Shrek", "Die Hard");
foreach ($movies as $movie) { echo "I watched $movie\n";}
FooLabGetting Index and Value
47
• In addition to the value, you can also get the index for each iteration:
foreach ($movies as $index => $movie)
FooLabConcatenation
48
• 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;
FooLabPractice!
• 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
FooLabAnswerfunction 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
FooLabTrivia
• 6 ^ 21 + 3 ^ 5gives over 20 quadrillions combinations
• It will take millions of years for a computerto try them all
• And you can pronounce it, making it easy to memorize!
51
FooLabNext Steps
• 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
FooLabResources
• php.net has a manual and a reference for all functions.
• phpquebec.org is the PHP users group in Montreal.
53