PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

94
PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark

Transcript of PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Page 1: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

PHP: ELOPING WITH PHP.NET

PA 70b – Giordon Stark

Page 2: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Table of Contents

Review of Last TimeIntroduction to PHP and www.php.net

Server Side versus Client SideXAMPP or UGCS

Can’t parse PHP if we don’t have this working.Getting our hands dirty

Simply put, the best way to learn is by doing. Echo, commenting, phpinfo Variables, Operators, Conditionals Includes, Requires For Loops, While Loops Generalized Functions

Practice Session

Page 3: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

BECAUSE NOT EVERYONE HAS PERFECT MEMORY RECALL.

A Review of Last Time

Page 4: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

What is JavaScript?

It’s a scripting language (not a markup language) A lightweight programming language

Adds interactivity to HTML pagesUsually embedded into HTML pages in identical

ways like CSS can be Inline JavaScript Internal JavaScript External JavaScript

Interpreted Language It executes without previous compilation (just like PHP)

It’s free (no license required)

Page 5: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Why is JavaScript awesome?

It has simple syntax for beginners – but can come with a steep learning curve for experts

It’s a reaction script – it can execute when something happens such as Load, double click, click, focus, blur, drag, right click,

enter, exit, scroll, mouse up, mouse down, key up, key down, key press, etc…

Unlike PHP, CSS, and HTML – it can interact directly with elements in your DOM It can alter attributes and values, the contents of an

element, rearrange your DOM, move or copy elements around

Page 6: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

jQuery is Unobtrusive

Example from before:<body>

<input type="text" onclick="this.value = Date()" /></body>

Becomes<head>

$(document).ready(function(){$("#date").click(function(){

$(this).val( Date() );});

});</head><body>

<input id= "date" type="text“ /></body>

Page 7: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

jQuery uses CSS Selectors

The jQuery wrapper!jQuery(selector)$(selector)

What do you think this does? $(‘p a’) $(‘p:last-child’)

And some actions (and chaining) $(‘div.notLongForThisWorld’).hide(); $

(‘div.notLongForThisWorld’).hide().addClass(‘removed’);

Page 8: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

The jQuery References

Selectors http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Events (click, hover, etc…) http://www.w3schools.com/jquery/jquery_ref_events.asp

Effects (hide, show, fade, animate, etc…) http://www.w3schools.com/jquery/jquery_ref_effects.asp

HTML Manipulation http://www.w3schools.com/jquery/jquery_ref_html.asp

CSS Manipulation http://www.w3schools.com/jquery/jquery_ref_css.asp

AJAX (we’ll cover this with PHP) http://www.w3schools.com/jquery/jquery_ref_ajax.asp

Misc http://www.w3schools.com/jquery/jquery_ref_misc.asp

Page 9: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

And we have…

From the very first lecture…

Page 10: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

“Other” TagsOther Tags and Inline (“Formatting”) Tags*

Anchor: <a></a>Link: <link></link>

Linking external stylesheetsBody: <body></body>Head: <head></head>HTML: <html></html>Image: <img></img>

Map: <map></map> Area: <area />

Style: <style></style>Script: <script></script>

Doc. Title: <title></title>DTD: <!DOCTYPE html>Span: <span></span>Strikethrough:

<del></del>Pre-formatting:

<pre></pre>Superscript: <sup></sup>Subscripts: <sub></sub>Examples of the Above: link

HTML Tags

*Note: these are OK for this class, but HTML is not meant to format a page, simply to organize it. Link

Page 11: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Block (“Layout “) Tags* Table Tags

Division: <div></div>Line Break: <br />Horizontal Line: <hr />Heading: <h#></h#>

#={1,2,3,4,5,6} 1 largest, 6 smallest

Paragraph: <p></p>Section:

<section></section>Article: <article></article>Aside: <aside></aside>

<table></table>Table Row: <tr></tr>Data Cell: <td></td>

<th></th> (for header row)Groups

Header: <thead></thead> Body: <tbody></tbody> Footer: <tfoot></tfoot>

Table Caption: <caption></caption>

HTML Tags

*We will not go over frames or inline frames in this class.

Page 12: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

List Tags Form Tags– Next Week!

Ordered List Start: <ol></ol> List Item: <li></li>

Unordered List Start: <ul></ul> List Item: <li></li>

Definition List Start: <dl></dl> Term: <dt></dt>

Description: <dd></dd>

<form></form> Input Control: <input />

<button></button> Text Area:

<textarea></textarea> Select List:

<select></select> Option: <option></option> Group: <optgroup></optgroup>

Label: <label></label> Fieldset:

<fieldset></fieldset> Legend: <legend></legend>

HTML Tags

Page 13: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

THE LANGUAGE OF WEB PROGRAMMERS WORLDWIDE!

Introduction to PHP

Page 14: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

A quick reminder

A lot of links used for the examples and exercises may refer to my website – where the code is “run”, but you can’t see the source (since the server parses the PHP before sending it to you)

Make sure you download the zip file included for the code

Page 15: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

What CAN PHP do?

http://www.php.net/manual/en/intro-whatcando.php

http://www.php.net/manual/en/funcref.phpOf most importance, we’ll cover topics in

PHP Options/Info — PHP Options and Information Date/Time — Date and Time Directories Mail Math — Mathematical Functions Sessions — Session Handling Text Processing Variable and Type Related Extensions

Page 16: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

History of PHP

http://www.php.net/manual/en/history.php.php PHP/FI 2.0 PHP: Hypertext Preprocessor

(don’t you love recursion?)

“PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.”

Page 17: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

What is PHP?

Server-Side Language HTML, CSS, JavaScript are all client-side (involves the

browser).It gets processed and parsed before it even

reaches the client

Page 18: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

GETTING IT TO WORK PROPERLY.IF YOU HAVE WINDOWS AND NO UGCS

ACCOUNT…

XAMPP

Page 19: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Problems with XAMPP?

The most problematic issue comes with the wrong port being selected in XAMPP.

Here’s the fix: Open httpd.conf file in your text editor. Find this line: Listen 80 Change it to: Listen 8080 Save and restart Apache.

Always restart Apache after making changes to a conf file.

http://locahost:8080 would now be your XAMPP default pages. You must always add :8080 to a url now.

Page 20: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

ACTUALLY, NOT REALLY… IT ’S TIME TO LEARN SOME PHP!

It’s Peanut Butter Jelly Time!

Page 21: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Your first PHP Script

With XAMPP running, let’s get things started http://www.ugcs.caltech.edu/~

kratsg/PA070b/Lecture6/example/exercise1.php Actual Code versus Source Code

What happened to it all? Whitespace? Line breaks? PHP Code? Functions used:

echo — Output one or more strings void echo ( string $arg1 [, string $... ] ) php.net/echo

“echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses. “

Page 22: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Language Constructs

“Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions. “

http://www.php.net/manual/en/functions.variable-functions.php

Page 23: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #1

Create a php page on your website, put in a php script block<?php

?>And then echo something

Page 24: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

2=3X+4, SOLVE FOR THE VARIABLE ‘X ’ .

Variables

Page 25: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Most Famous PHP Code

It’s also the most dangerous… you have been warned! Try it yourself! phpinfo();

http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exercise2.php

Provides useful information about your system and setup such as available predefined variables loaded PHP modules configuration settings

Page 26: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

Stores a valueReused throughout your codeCan be thought of as a programming construct used to

store both numeric and non-numeric dataContents can be altered during program executionCan be compared with each otherSome Types of variables

integers, floating point numbers, strings and arraysWhat makes it different than all other languages?

In many languages, it's essential to specify the variable type before using it: for example, a variable may need to be specified as type integer or type array. Give PHP credit for a little intelligence, though: it automagically determines variable type by the context in which it is being used!

Page 27: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

All variables are defined with the dollar sign ($) $<<variable name>>

Some proper rules PHP variables must start with a letter or underscore "_". PHP variables may only be comprised of alpha-numeric

characters and underscores. a-z, A-Z, 0-9, or _ . Variables with more than one word should be separated

with underscores. $my_variable Variables with more than one word can also be

distinguished with capitalization. $myVariable Variables are case-sensitive

$foo != $Foo != $FOO

Page 28: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

Let’s see an example of assigning values to variables

http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exercise3.php How to set variables and the ‘automagic’ feature! We also see variable dump being used to examine the

variables we’ve set.http://www.ugcs.caltech.edu/~kratsg/PA070b/

Lecture6/example/exercise4.php What if we have a string? How can it be an integer?!

Page 29: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

What types are there? Boolean (true or false)

$authVar = true; Integer (whole number)

$age = 99; Floating-point (not a whole number)

$decimal = 3.1415926; String (always contained in quotes)

$identity = ‘James Bond’; $sentence = “$identity is 007.”;

Other data types http://www.php.net/manual/en/language.types.php

Page 30: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

What was going on with that james Bond thing? $identity = ‘James Bond’; $sentence = “$identity is 007.”

We are inserting the value of $identity into $sentence. Try the following example:$identity = ‘James Bond’;echo “$identity is 007.”;echo ‘$identity drives cars and snags hot women.’;

http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exercise5.php

Quotations make all the difference! Single quotes are literal – using them is like saying that everything

inside is a string, no replacement necessary Double quotes are not literal – use them if you have variables that

need replacement (you are telling PHP that you want it to grab the value of that variable and use it in the string)

Page 31: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #2

Try echoing the following statement:

In the words of Forrest Gump, “My momma always said, "Life was like a box of chocolates. You never know what you're gonna get.”

Page 32: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

Quotes can lead to many of the common errors in codes

Echo uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations: Don't use quotes inside your string (what if you need

quotes?) Escape your quotes that are within the string with a

backslash. To escape a quote just place a backslash directly before the quotation mark, i.e. \"

Use single quotes (apostrophes) for quotes inside your string http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/exampl

e/exercise6.php

Page 33: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #2, Revisited

Now that you’re wiser… try echoing the following statement:

In the words of Forrest Gump, “My momma always said, "Life was like a box of chocolates. You never know what you're gonna get.”

Page 34: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

We can combine strings together with variables and then output them, this is called concatenation. Concatenation operator is the period (.)

We can do anything we really want, we have free rein…

Combining variables, strings, and outputs http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/

example/exercise7.phpWhat if you wanted to automatically add line

breaks to a string? Or extra characters? http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/

example/exercise8.php

Page 35: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #3

How many different sentences can you make using the following words and string concatenation? (Hint, use some well-placed commas)

$a = “Man”;$b = “Woman”;$c = “without”;$d = “is”;$e = “nothing”;

Page 36: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

String Operators

I’ve created my own example, demonstrating how awesome and useful string concatenation is. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise9.phpFor more information on string operators

http://www.php.net/manual/en/language.operators.string.php

Page 37: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

SILLY STRING, STRING THEORY, STRINGING YOU GUYS ALONG…

Strings

Page 38: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Strings

We have used double-quotes and will continue to use them as the primary method for forming strings.

Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. $newline = "A newline is \n“; $return = "A carriage return is \r“; $tab = "A tab is \t“; $dollar = "A dollar sign is \$“; $doublequote = "A double-quote is \"";

Once again, a backslash is used to escape a character. If you try to escape something that does not need to be

escaped, it will display the backslash as well… Try escaping a backslash!

Page 39: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Strings

The Heredoc! Many times, you will want to output a giant block of HTML that takes up multiple lines… http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture6/example/exercis

e10

There are a few very important things to remember when using heredoc. Use <<< and some identifier that you choose to begin the heredoc. Repeat the identifier followed by a semicolon to end the heredoc string

creation. The closing sequence must occur on a line by itself and cannot be

indented!Another thing to note is that when you output this multi-line

string to a web page, it will not span multiple lines because we did not have any <br /> tags contained inside our string!

Page 40: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #4

Using the Heredoc, store the following multi-line output in a variable, and then echo it on the page.

<html><head>

<title>Hello World!</title></head><body>

HTML, I am your body…</body>

</html>

Page 41: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

OPERATOR, OPERATOR, WHAT’S THE NUMBER FOR 911?

Operators

Page 42: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Assignment Operators

Assignment Operators Assignment operators are used to set a variable equal

to a value or set a variable to another variable's value.Always done with the ‘=‘ character. We’ve

seen a lot of examples already.

Page 43: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Arithmetic Operators

Arithmetic Operators http://www.php.net/manual/en/language.operators.arithm

etic.php

Example Name Result

-$a Negation Opposite of $a.

$a + $b Addition Sum of $a and $b.

$a - $b Subtraction Difference of $a and $b.

$a * $b Multiplication Product of $a and $b.

$a / $b Division Quotient of $a and $b.

$a % $b Modulus Remainder of $a divided by $b.

Page 44: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Comparison Operators

Comparisons are used to check the relationship between variables and/or values.

They always return the Boolean variable type $x=4, $y=5

Operator English Example Result

== Equal To $x == $y false

!= Not Equal To $x != $y true

< Less Than $x < $y true

> Greater Than $x > $y false

<= Less Than or Equal To $x <= $y true

>= Greater Than or Equal To

$x >= $y false

Page 45: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #5

Try out each of the comparison operators yourself and determine the result. The first one is done for you:

$a=5;$b=6;$c=1;var_dump($a==$b);//should be boolean falsevar_dump($c==($b-$a));//should be boolean

true

Page 46: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

String Operators

The period is the concatenation operatorIt adds concatenates two strings together

Page 47: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Variables

With integers, we can automatically increment a number: $number = 5; $number++;//6

Does the same as $number = $number +1; $number--;//5

Does the same as $number = $number -1;

If you wanted to increment by a different number, we can use a similar shortcut as we saw with string concatenation $number += 5;

Does the same as $number = $number +5;

Page 48: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Combinations of Operators

Sometimes you want to have a ‘counter’ variable so that you increment by one: $counter = $counter +5;

The better/shortcut way of doing this is: $counter +=5;Operator English Example Equivalent Operation

+= Plus Equals $x += 2; $x = $x + 2;

-= Minus Equals $x -= 4; $x = $x - 4;

*= Multiply Equals $x *= 3; $x = $x * 3;

/= Divide Equals $x /= 2; $x = $x / 2;

%= Modulo Equals $x %= 5; $x = $x % 5;

.=Concatenate Equals

$my_str.="hello";

$my_str = $my_str . "hello";

Page 49: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Pre/Post Operators

Again, let’s say you have a counter that you want to increase or decrease by 1. We can use the ‘++’ operator. (Decreasing is the ‘--’ operator).

We can either put this operator before or after the variable and this has an effect on when it increments/decrements the value. http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise11

Page 50: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

NOT CRITICISMS!

Comments

Page 51: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Just a reminder

As you’re starting down the road towards making many future and more complicated PHP projects, don’t forget to always comment.

Here are some funny comments found in programming…

Page 52: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

/*** For the brave souls who get this far: You are the chosen ones,* the valiant knights of programming who toil away, without

rest,* fixing our most awful code. To you, true saviors, kings of men,* I say this: never gonna give you up, never gonna let you down,* never gonna run around and desert you. Never gonna make

you cry,* never gonna say goodbye. Never gonna tell a lie and hurt you.*/

Page 53: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

// // Dear maintainer:// // Once you are done trying to 'optimize' this routine,// and have realized what a terrible mistake that was,// please increment the following counter as a warning// to the next guy:// // total_hours_wasted_here = 16//

Page 54: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

stop(); // Hammertime!// sometimes I believe compiler ignores all my

comments//When I wrote this, only God and I understood

what I was doing. Now, God only knows// Magic. Do not touch.return 1; //returns 1long john; // silver<!-- Here be dragons -->

Page 55: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

// Replaces with spaces the braces in cases where braces in places cause stasis $str = str_replace(array("\{","\}")," ",$str);

long long ago; /* in a galaxy far far away *//* Halley's comment *//* Please work *///Dear future me. Please forgive me.

//I can't even begin to express how sorry I am.  ////////////////////////// this is a well commented line

Page 56: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

IT ’S LIKE CITATION… BUT SO MUCH EASIER!

Including Files

Page 57: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Includes

Takes a file name and simply inserts that file's contents into the script that issued the include command

Efficient? Common Header for all files, regardless! Instead of having to update the links on several web

pages, you can simply change the header file

Page 58: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Requires

Just like includes, but one major differenceWhen you include a file with the include

command and PHP cannot find it you will see an error message like the following (example 12) http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise12The rest of the file executed… maybe we

don’t want this. If we change the command to require, what happens?

Page 59: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #7

Try it yourself! What happens if you include a text document? Image file?

Page 60: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

I ’LL TELL YOU EVERYTHING YOU NEED TO KNOW, BUT ONE ON CONDITION…

Conditionals

Page 61: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Conditionals

Why do we care about conditionals? They’re the heart and soul of PHP, providing the

means to make your script interactive and responsive to inputs

The result of a comparison test is always Boolean: either true (1) or false (0 - which doesn't print anything).

Page 62: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Comparison, PHP4.0

As of PHP4.0, there’s a new comparison operator (which I call congruency) which checks for equality and type of variable ‘===‘ (triple equal) http://www.ugcs.caltech.edu/~kratsg/PA070b/Lecture

6/example/exercise13A full list (on next page) taken from

http://www.php.net/manual/en/language.operators.comparison.php

Page 63: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Comparison Operators

Example Name Result

$a == $b Equal TRUE if $a is equal to $b.

$a === $b IdenticalTRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)

$a != $b Not equalTRUE if $a is not equal to $b.

$a <> $b Not equalTRUE if $a is not equal to $b.

$a !== $b Not identical

TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)

$a < $b Less thanTRUE if $a is strictly less than $b.

$a > $b Greater thanTRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Page 64: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Logical Operators

The conditional is a statement which we evaluate using comparison operators If you wish to evaluate multiple statements at the

same time, use logical operators http://www.php.net/manual/en/language.operators.logi

cal.php

Example Name Result

$a and $b And TRUE if both $a and $b are TRUE.

$a or $b Or TRUE if either $a or $b is TRUE.

$a xor $b XorTRUE if either $a or $b is TRUE, but not both.

! $a Not TRUE if $a is not TRUE.

$a && $b And TRUE if both $a and $b are TRUE.

$a || $b Or TRUE if either $a or $b is TRUE.

Page 65: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #7

Convert the following statements to conditionals and evaluate using var_dump(); function.

Assume $a=5, $b=6, $c=1

$a and $c are odd or $b is even$a and $c are odd xor $b is even$a >$b or $b>$c or $c>$a

Does this last statement ALWAYS evaluate true for any $a,$b,$c?

Page 66: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

If

Take the following codeif(conditional1) {

//do this when conditional1 is true}

Page 67: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

If, Else

Take the following codeif(conditional1) {

//do this when conditional1 is true} else {

//do this when conditional1 is false}

Page 68: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

If, Elseif, Else

Take the following codeif(conditional1) {

//do this when conditional1 is true} else if(conditional2) {

//do this when conditional2 is true} else {

//do this when both conditional1 and conditional2 are false

}

Page 69: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Conditional Example

Properties of a triangle: length of 2 sides always greater than third side.

Property of a right triangle: a^2+b^2=c^2 (Pythagorean’s Theorem)

Variables: $a,$b,$c = length of sides of triangle (integer)

if($a+$b < $c || $a+$c < $b || $b+$c < $a){echo “That is not a triangle!”;

} else if($a^2+$b^2==$c^2 || $a^2+$c^2==$b^2 || $b^2+$c^2==$a^2){echo “That is a right triangle!”;

} else {echo “That’s a regular triangle.”;

}

Page 70: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #8

Create a PHP script analog of the following statements.

Variables: $hungry/$cook = true or false (boolean) If I am hungry and I can cook, I will make spaghetti and

meatballs. If I am hungry and I cannot cook, I will order Chinese takeout. If I am not hungry, I will sleep.

Variables: $drink = type of drink (string), $age = age of person (integer) If I am drinking soda, then tell me not to drink so much. If I

am under 21 and I am drinking alcohol, then nobody is happy. If I am over 21 and I am drinking alcohol, then tell me not to drink so much. (Bonus points if you use an XOR conditional)

Page 71: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

One Last Example

Try making an If,Elseif,Else conditional for the following

Variables: $state = state user is traveling to (string)

If they’re going to Florida, flight time is 5 hours. If they’re going to (…), flight time is (…) hours…. [do this for all 50 states].

Page 72: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Switch Statements

STOP RIGHT THERE! Doesn’t that seem inefficient? Of course it does! That’s why I tried to get you to do it. Luckily, to improve efficiency, we have switch statements. You would have to check with a nasty long block of

If/ElseIf/ElseIf/ElseIf/... statements. This doesn't sound like much fun to code…

The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

There is also a default case, when all the other cases don’t match our input.

Page 73: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

One Last Example (revisited)

The code might look something like thisswitch($state){

case “Florida”:echo “It’ll be a quick 5 hour flight!”;

break;case “California”:

echo “You’re already there silly!”;break;…default:

echo “You’re going out of country? Expect at least a 10 hour flight buddy…”;

break;

Page 74: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

A Special Trick…

If the thought of confusing people who read your code makes you feel warm and tingly, you're going to love the ternary operator, represented by a question mark (?). This operator, which lets you make your conditional statements almost unintelligible, provides shortcut syntax for creating a single-statement if-else block.

For Example if ($numTries > 10) {

     $msg = 'Blocking your account...';     } else {     $msg = 'Welcome!'; }

Can be replaced with $msg = $numTries > 10 ? 'Blocking your account...' : 'Welcome!';

Page 75: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

ROLLER COASTERS JUST AREN’T THE SAME ANYMORE…

Loops

Page 76: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Loops

What ARE they? a loop is a control structure that enables you to repeat

the same set of php statements or commands over and over again (the actual number of repetitions can be a number you specify, or depend on the fulfillment of one or more conditions)

What will I need? Combination Operators: auto-increment (++) and

auto-decrement (--) are of utmost importance.What kinds of loops are there?

While, Do-While, and For

Page 77: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

While Loops

While loops Depends on a conditional While some condition is true, keep looping.while(condition is true) {

//do something} The following while loop prints out all even numbers

(multiples of two) between two numbers, $upper and $lower:

while($upper >= $lower){if(!$lower%2){echo $lower.’<br />’;}$lower++;

}

Page 78: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #9

Use a while loop to print out squares of all ODD numbers between two numbers (upper and lower).

Page 79: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Do-While Loops

Like while loops Depends on conditional Keeps looping while some condition is true Always runs at least once (even if the condition is false)do {

//do something} while(condition is true); The following do-while loop runs at least once (assume

$upper<$lower):do {

if(!$lower%2){echo $lower.’<br />’;}$lower++;

} while($upper >= $lower);

Page 80: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

For Loops

Both the while() and do-while() loops continue to iterate for as long as the specified conditional expression remains true.

But what if you need to execute a certain set of statements a specific number of times? Clever programmers like me reach into our toolbox for

the for() Loop

for (initial counter value; condition; new counter value) {//do this

}

Page 81: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

For Loops

They are very powerful and allows one to create large outputs of repetitive HTML with very little PHP coding involved. As an example, remember the <sup> tag? Let’s make a loop that nests 100 of them!

$opening = null;$closing = null;for($i=0;$i<100;$i++){

$opening .= ‘<sup>’;$closing .= ‘</sup>’;

}

echo $opening.’I\’m nested!’.$closing;

Page 82: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #10

Fun with tables! You might have guessed that this is a fancy way to generate any size table you would like. Using a for-loop inside a for-loop, create a script that takes an arbitrary number of rows $rows and arbitrary number of columns $columns to create a table.

Some hints: Don’t need to store anything html-related inside

variables, just simply use the echo language construct inside the actual loops.

Page 83: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

CONJUNCTION JUNCTION, WHAT’S YOUR FUNCTION?

Functions

Page 84: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

A function is… "a block of statements that can be grouped together as a named

entity.“ a set of program statements which perform a specific task, and which

can be "called", or executed, from anywhere in your programWhy are functions good?

user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug

functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program

functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition)

Functions thus save time, money and electrons... and I know the electrons at least will thank you!

Page 85: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

As an example, try out the following function.function AreYouBusy() {

    echo “I’ve got all the time in the world."; } Then, each time you call the functionAreYouBusy();It runs, and in our case, would echo out “I’ve

got all the time in the world.”

Page 86: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

Here’s a typical structure of a functionfunction function_name (optional arguments) {

    statement 1...     statement 2...     .     .     .     statement n...

}

Page 87: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

Let’s say you want to pass in arguments to the function, make it more flexible and dynamic.

function CircleCircum($radius=‘0’) {$circum = 2*Pi*$radius;echo “The circumference of a circle with radius $radius is $circum.”;

}The function CircleCircum() has one argument $radius

which has a defined default value of ‘0’. Your arguments do not need a default value. Call the function like so:

CircleCircum(10);CircleCircum(20);

Page 88: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

More than one argument? Sure! Just separate them with commas.function adder($a,$b){

$sum = $a+$b;return $sum;

} Just call it like so$sum = adder(6,3);echo ‘The sum is ‘.$sum;//The sum is 9 What’s unique about this particular function is that instead of

echoing a value to the screen, it returns that value… In a manner of speaking, the result is returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.

You can run it inside another function like soecho ‘The sum is ‘.adder(6,3);//The sum is 9

Page 89: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

A function can return any type of value. If a variable can hold it, it can return it. The possibilities are limitless.

Don’t forget that arguments are called in order and unless they have a default value, they need to be specified.

function divider($a,$b=‘2’){$divide = $a/$b;return $divide;

}Here, this function has two arguments. Interchanging them

obviously changes the result (unless both numbers were the same!) Because of the default value, we can call it with one argument

divider(3);//returns 1.5

Page 90: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Short Exercise #12

Using the table-loop code that you made previously, put this into a function with two arguments ($rows, $cols) and see how you can reuse the same code.

function createTable($rows,$cols){…

}

createTable(20,10);

Page 91: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Functions

That’s all we’ll cover on functions for this week. Next week, we’ll cover the globality/locality of variables used within functions and having variables be "passed by reference" or "passed by value“.

Page 92: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

PRACTICE MAKES PERFECT, BUT NOBODY’S PERFECT… WHY PRACTICE?

Practice Session / Homework

Page 93: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

Homework

Keep working on your websites and adding in jQuery

Page 94: PHP: ELOPING WITH PHP.NET PA 70b – Giordon Stark.

The FizzBuzz Test!

Some background information on FizzBuzz http://imranontech.com/2007/01/24/using-fizzbuzz-to-fin

d-developers-who-grok-coding/ “The majority of comp sci graduates can't. I've also

seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution.” http://www.codinghorror.com/blog/2007/02/why-cant-progr

ammers-program.html

The FizzBuzz Challenge Write a program that prints the numbers from 1 to 100.

But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".