PHP 101

By Margaret May

Organized by Elena Levine

Partially based on a GDI class created by Sylvia Richardson

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Be considerate of others.
  • Help each other.
This and all following slides: https://github.com/Roenok/gdi-intro-php-mysql

What we will cover today

  • Refresher
  • Beginner debugging
  • Variables
  • Control Flow
  • Arrays

------ Beginner Debugging ----

Debugging your code

Not seeing anything when you run your code? You may need to turn on error logging. Put this code at the top of your page.


	<?php
	// Report all PHP errors
	error_reporting(-1);
	?>
				

------ Refresher ----

Let's Look Back

Woman looking backward as she dances

Photo credit: Deepak Bhatia cc

Code Search

In this code, spot the comments, variables, operator, function, argument, and return value.


<?php
    function calculateTip($total) {
        $tipPercent = 0.15; //Can be changed
        return ($total * $tipPercent);
    }

    $billTotal = 10;
    $billTip   = calculateTip($billTotal);
    $receipt   = 'Meal: ' . $billTotal . ' Tip: ' . $billTip . 
        ' Total: ' . ($billTotal + $billTip);
    echo $receipt; 
?>
				

------ Variables ----

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.


<?php
    $awesomeGroup = 'Girl Develop It'; //Global scope
    function whatIsAwesome() {
        echo $awesomeGroup . ' is pretty awesome.';
    }
    whatIsAwesome();
?>
				

Local Scope

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


<?php
    function whatIsAwesome() {
        $awesomeGroup = 'Girl Develop It'; //Local scope
    }
    echo $awesomeGroup . ' is pretty awesome.';
?>
				

Boolean Variables

Kitten with light switch

Photo credit: elycefeliz cc

Boolean Variables

Boolean variables represent the logical values True and False


<?php
    $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 ----

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.


<?php
if (condition) {
  // statements to execute
}
?>
				

<?php
$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

Exercise! Let's Develop It

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

Click here to run my answer!

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.


<?php
    $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.


<?php
    $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.';
    }
?>
				

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.

Click here to run my answer!

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.


<?php
    $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.

Click here to run my answer!

------ Loops ----

Loops

Kitten in ball

Photo credit: Courtney Patubo Kranzke cc

While loops

While will repeat the same code over and over until some condition is met.


<?php
    $bottlesOfBeer = 99;
    while ($bottlesOfBeer >= 1) {
        echo $bottlesOfBeer . ' bottles of beer on the wall <br />';
        $bottlesOfBeer = $bottlesOfBeer - 9;
    }
?>
				

Infinite Loops

Make sure something changes in the loop, or your loop will go on forever...

Spiral that goes on toward infinity

Photo credit: Samuel John cc

For loops

For loops are very similar, but you declare a counter in the statement.


<?php
    //will count 1 to 10
    for ($i = 1; $i <= 10; $i++) {
        echo $i; 
    }
?>
				

Loops and logic

You can add other statements or logical operators inside the loops.


<?php
    //Count from 1 to 50.
    for ($i = 1; $i <= 50; $i++) {
        echo $i;        
        //Says 'Buzz' after multiples of three
        if ($i%3 == 0) {
            echo ' Buzz';
        }        
        //Says 'Bang' after multiples of five
        if ($i%5 == 0) {
            echo ' Bang';
        }        
        echo '<br />'; //line break
    }
?>
				

Let's Develop It

Write a loop that gives you the 9's times table,
from 9 x 1 = 9 to 9 x 12 = 108.

Bonus: Try using a loop inside a loop to write all the times tables, from 1 to 12.

Click here to run my answer!

Click here to run my answer to the bonus!

------ Arrays ----

Arrays

Group of kittens

Photo credit: Jesus Solana cc

Arrays

Arrays are lists of values associated with a key. The key needs to be an integer or a string, the value can be any type.


<?php
    $kittenColors = array(
        'Fluffy' => 'tabby',
        'Midnight' => 'black',
        'Admiral Snuggles' => 'white',
    );
?>
				

Using arrays

Once you have an array, you use a key to call a value.


<?php
    $kittenColors = array(
        'Fluffy' => 'tabby',
        'Midnight' => 'black',
        'Admiral Snuggles' => 'white',
    );
    echo $kittenColors['Midnight']; //prints 'black'
?>
				

Expanding arrays

Arrays don't have a fixed length; you can add and take away items.


<?php
    $kittenColors = array(
        'Fluffy' => 'tabby',
        'Midnight' => 'black',
        'Admiral Snuggles' => 'white',
    );
    
    // This adds a new element to the array with key 'Monster'
    $kittenColors['Monster'] = 'gray'; 
    
    // This removes the element with the key 'Midnight'
    unset($kittenColors['Midnight']);    
?>                
                

Arrays without keys

If you don't specify a key, PHP will just automatically assign integers as keys, starting with zero.


<?php
    $fruits = array("apple", "orange", "banana", "kiwi");
    var_dump($fruits); //shows whole array
    echo $fruits[1]; //will print orange
    
    //You can add with no key as well
    $fruits[] = 'mango';
    var_dump($fruits);    
?>                
                

Let's Develop It

Create an array of your friends and their favorite foods. Echo a few values onto your screen.

Click here to run my answer!

Foreach

Couple holding hands

Photo credit: John cc

Foreach loops

Foreach is a special type of loop that works with arrays.


<?php
    $numberList = array(1, 2, 3, 4, 5);
    foreach ($numberList as $value) {
        echo $value . ' times 2 equals ' . ($value*2) . '<br />';
    }
?>  
				

Arrays with keys

You can also use the key values in your foreach loop.


<?php
    $kittenColors = array(
        'Fluffy' => 'tabby',
        'Midnight' => 'black',
        'Admiral Snuggles' => 'white',
    );
    
    foreach ($kittenColors as $name => $color) {
        echo 'The kitten ' . $name . ' has ' . $color . ' fur.<br />';
    }
?>  
				

Let's Develop It

Take your array of friends and write a foreach loop that echos "My friend NAME likes FOOD."

Click here to run my answer!

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.

Homework

  • Let's expand My Packing Helper from the first homework assignment. Create a trip information array that contains information about your trip, including but not limited to Destination, Number of Travel Days, Mode of Transit, Purpose of Travel, and so forth. Write a displayTripInfo function to display this travel information.
  • Write a function that will take your trip information array and will output 'Wow, this is going to be a long trip!' if the number of travel days is 7 or more, or 'This will be a good amount of time to be away' if travel days is between 5 and 3 days, or 'This will be a whirlwind trip' if travel days is 2 or less.