BDI Logo

Introduction to PHP

Class 2

Let's Look Back

Woman looking backward as she dances

Photo credit: Deepak Bhatia cc

Code Search

In this code, spot the comments, variables, and operators.

$billPreTip = 25.35;
$tipPercentage = 0.20; //Can be changed
$totalBill = $billPreTip * (1 + $tipPercentage);
echo "Your total bill, with tip, is \$$totalBill.";

Do you see an escaped character? What else do you notice about the code?

Functions

Functions are separable, reusable pieces of code. Pile of legos

Photo credit: Rick Payette cc

Declaring Functions

To declare (create) a function, you give it a name. You then include all the code for the function inside curly brackets:

function turtleFacts() {
  echo '

A turtle\'s lower shell is called plastron.

'; echo '

Turtles belong to the order Testudines

'; }

Function can have multiple lines.

Using Functions

To use a function, just type its name, followed by parenthesis.

turtleFacts();

We'll talk about what can go inside those parenthesis in a minute! For now, leave them empty.

What's going on here?

A function is a group of code you can reuse many times. Whenever you call a function by using it's name, you tell the server to run the code inside the function.

You must declare a function before you can use it.

Let's Develop It

Write a function that outputs a sentence. Then call that function later in your code.

Arguments

Functions can accept input values, called arguments.

function callKitten ($kittenName){
  echo "Come here, $kittenName!";
}
callKitten ('Fluffy'); //outputs 'Come here, Fluffy!'

function addNumbers($a, $b) {
  echo $a + $b;
}
addNumbers(5,7); //outputs 12
addNumbers(9,12); //outputs 21

Arguments

You can also pass variables into functions. These variables do not need to have the same name as the function arguments.

function addOne($inputNumber){
  $newNumber = $inputNumber + 1;
  echo "<p>You now have $newNumber</p>";
}

//Declare variables
$numberOfKittens = 5;
$numberOfPuppies = 4;

//Use them in functions
addOne($numberOfKittens);
addOne($numberOfPuppies);

Let's Develop It

Write a function to say hello! This program should:

  • Accept two arguments, a first name and a last name.
  • Output a sentence like this "Hello [Name]. It's nice to meet you!"

Don't forget to test your function out with some different names!

Returning Values

You can have a function give you back a value, to use later.

function square($num) {
  return $num * $num;
}
echo square(4);   // outputs '16'.
$squareOfFive = square(5); // will make $squareOfFive equal 25.

Return will immediately end a function.

Let's Develop It

Add a return statement to your Hello function. Use that function to set the value of a variable.

Variable Scope

The scope of a variable is how long the computer will remember it.

Footprints being washed away

Photo credit: _vikram cc

Global Scope

A variable declared outside a function has a global scope and can only be accessed outside a function.

$awesomeGroup = 'Girl Develop It'; //Global scope
function whatIsAwesome() {
  echo "$awesomeGroup is pretty awesome."; //This will fail
}
whatIsAwesome();

Local Scope

A variable declared within a function has a local scope and can only be accessed within that function.

function whatIsAwesome() {
  $awesomeGroup = 'Girl Develop It'; //Local scope
  echo "$awesomeGroup is pretty awesome."; //This will work
}
whatIsAwesome();

Boolean Variables

Kitten with light switch

Photo credit: elycefeliz cc

Boolean Variables

Boolean variables represent the logical values True and False

$catsAreBest = true;
$dogsRule = false;

If you try to use another variable as a boolean, PHP will guess. The number 0, the empty string '', and the string '0' are considered false, everything else reads as true.

Control Flow

Forked path

Photo credit: DennisM2 cc

The if statement

Use if to tell PHP which lines of code to execute, based on a condition.

if (condition) {
  // statements to execute
}
$bananas = 5;
if ($bananas > 0) {
  echo 'You have some bananas!';
}

Comparison Operators

Example Name Result
$a == $b Equal TRUE if $a is equal to $b (can be different types).
$a === $b Identical TRUE if $a is equal to $b, and the the same type.
$a != $b Not equal TRUE if $a is not equal to $b (can be different types).
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not the same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE 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.

Watch out!

Don't mix up = and ==

Caution Tape

Photo credit: Eugene Zemlyanskiy cc

Let's Develop It

Make a variable called "temperature." Write some code that tells you to put on a coat if it is below 50 degrees.

Even more control flow

Sign post with multiple signs

Photo credit: Thomas Hawk cc

The if/else statement

Use else to provide an alternate set of instructions.

$age = 28;
if ($age >= 16) {
  echo 'Yay, you can drive!';
} else {
  echo 'Sorry, but you have ' . (16 - $age) .
  ' years until you can drive.';
}

The if/else if/else statement

If you have multiple conditions, you can use else if.

$age = 20;
if ($age >= 35) {
  echo 'You can vote AND hold any place in government';
} else if ($age >= 30) {
  echo 'You can vote AND run for the Senate';
} else if ($age >= 18) {
  echo 'You can vote';
} else {
  echo 'You can\'t vote, but you can still
  write your representatives.';
}

Switch statments: Numbers

If you need to match numbers against a fixed set, you can also use a switch. You can only use a switch to check for equal values, without comparison operators.

$i = 1;
switch ($i) {
  case 0:
    echo "i equals 0";
    break;
  case 1:
    echo "i equals 1";
    break;
  case 2:
    echo "i equals 2";
    break;
  default:
   echo "i is not equal to 0, 1 or 2";
}

Switch statments: Strings

You can also use switch statements with strings.

$fruit = 'banana';
switch ($fruit) {
  case 'apple':
    echo 'Mmm, an apple';
    break;
  case 'banana':
    echo 'I love bananas!';
    break;
  case 'cantalope':
    echo 'Cantalope is delicious';
    break;
  default:
   echo 'I don\'t understand this fruit';
}

Switch statments: Break

A break statement stops the switch. If you omit the break, it will execute the next comparison as well. You can also leave a case blank to keep moving

$i = 0;
  switch ($i) {
  case 0:
    echo 'i is 0';
  case 1:
  case 2:
    echo "i is less than 3 but not negative";
    break;
  case 3:
    echo "i is 3";
  }

Let's Develop It

Modify your "wear a coat" code for these conditions:

  1. If it is less than 50 degrees, wear a coat.
  2. If it is less than 30 degrees, wear a coat and a hat.
  3. If it is less than 0 degrees, stay inside.
  4. Otherwise, wear whatever you want.

Logical Operators

Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.

Using logical operators

You can use these operators to combine conditions.

$bananas = 5;
if ($bananas >=2 && $bananas <7) {
  echo 'You have a reasonable number of bananas';
} else {
  echo 'Check your banana supply';
}

Let's Develop It

Add a logical operator to your what to wear program.

Setting up PHP

Starting next class, we will be using your computer instead of PHP Fiddle. This means you will need to install PHP on your machine. Before the next class, please download and install WAMP (Windows) or MAMP (Mac).

You did it!

Happy cat

Photo credit: OnceAndFutureLaura cc

Resources

  • PHP Manual, the official PHP documentation. Check the comments; they are useful.
  • Code Academy, with interactive PHP lessons to help you review.