GETTING STARTED WITH  PHP

Hello World and Beyond!

June 20th 2015

Follow along: 

http://bit.ly/1JQUSph

Created by Juan Manuel Torres / @onema

Juan Manuel Torres

Born and raised in Bogotá Colombia

Software Engineer

MS Computer Science SDSU, 6+ years of experience 

Started using PHP in 2000

Started programming in 1999

How this presentation works

  • Use the link to follow the presentation http://bit.ly/1JQUSph
  • Use the orange links to access resources
  • Follow my instructions!
  • If you see this icon, you can see working code example

Overview

  • Create a GitHub Account
  • Create a Cloud 9 Account
  • What is a computer program?
  • What is PHP?
  • Writing your first script "Hello, World!"
  • Variables in PHP
  • Data types in PHP
  • Operators in PHP

If we have time

  • Arrays in PHP
  • Flow control, If and Else statements
  • Loops, for, foreach, while, do-while
  • Create a simple web page

Create a GitHub Account

What is GitHub?

 

  • GitHub is a hosted Git service (version control system)
  • It is very popular for hosting Open Source projects
  • It is used to "Sign in with GitHub" to a lot of development Tools 

Create a GitHub Account

Pick a Username / Password & SELECT A FREE ACCOUNT

Fork the Repository

Create a Cloud 9 Account

Create a Cloud 9 Account

Create a Cloud 9 Project

Create a Cloud 9 Project

Create a Cloud 9 Project

Create a Cloud 9 Project

What is a Computer Program?

Computer programs are collections of instructions that tell a computer how to interact with the user, the computer hardware or process data [1]

What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development [2]

Unlike other scripting languages that run directly in your computer, PHP will almost always run on a server.

Writing our first program

"Hello, World!"

The "Hello, World!" program is the simplest program you can write in any programming language. All it does is output "Hello, World!" [3]

Writing our first program

"Hello, World!"

<?php


// A simple web site in Cloud9 that runs through Apache ...
// THESE ARE COMMENTS AND WILL BE IGNORED BY PHP
/* 
   USE THE "/*" FOR 
   MULTILINE COMMENTS
*/



print 'Hello world from Cloud9!';



?>

With our "php-intro-workshop" project there is a sample hello-world.php file

PHP Open tag: tells the computer where the php program starts

  • "echo" or "print" to the screen
  • Anything in the quotes is a "string"
  • the ';' tells php the end of the command

PHP only files do not require a closing php tag

Variables

A variable is a storage location associated with a name.  Variables contain an unknown quantity or information called value [4]

<?php
// 01.simple_variable.php

$name = 'Juan';
$x = 30;
$y = 1.123;

// print the values below
print "";

Rules for PHP Variables [5]

  • A variable starts with the $ sign, followed by the name of the variable.
  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

Using PHP Variables [5]

<?php
// 02.hello_name.php

$name = 'Juan';
print "Hello, $name!";
/** 
 * This will output:
 * Hello, Juan!
 */

Data Types

A Data Type Is classification identifying one of various types of data [6]

Data Types

PHP Defines eight data types [7]

 

  • Four scalar types:
    • boolean (true or false)
    • integer (negative & positive non factional numbers & zero)
    • float (floating-point number, aka double)
    • string  (a series of characters)
  • Two compound types:
    • array (we'll get to arrays later)
    • object (we won't get to objects)
  • And finally two special types:
    • resource (we won't get to resource)
    • NULL (variable with no value)

Data Types

<?php
// 03.data_types.php

print gettype(true)      . PHP_EOL;      // bolean
print gettype(12345)     . PHP_EOL;      // integer
print gettype(1.2345)    . PHP_EOL;      // double
print gettype("Hello")   . PHP_EOL;      // string
print gettype([1, 2, 3]) . PHP_EOL;      // array
print gettype(new stdClass()) . PHP_EOL; // object
print gettype(null)      . PHP_EOL;      // NULL

PHP_EOL is a constant that represents the "End Of Line" symbol.

Operators

An operator in a programming language is a symbol that tells the [computer] to perform specific mathematical, relational or logical operation and produce final result. [8]

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value. [9]

Arithmetic Operators

-$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.
$a ** $b Exponentiation Result of raising $a to the $b'th power.

Assignment Operator

<?php
// 04.assignment_operator.php
$a = 1;
$b = 2;
$three = $a + $b;

print $three;

The assignment operator "=" is used to assign a value to a variable. It is not used to compare!

Comparison Operators


 

$a == $b Equal TRUE if $a is equal to $b
$a === $b Identical TRUE if $a is equal to $b
$a != $b Not equal TRUE if $a is not equal to $b
$a !== $b Not identical TRUE if $a is not equal to $b 
$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 .

 

Comparison Operator

<?php
// 05.comparison_operators.php

var_dump(1 == 2);       // FALSE
var_dump(1 < 2);        // TRUE
var_dump(1 <= 2);       // TRUE
var_dump(2 > 2);        // FALSE
var_dump(2 >= 2);       // TRUE
var_dump(1 == true);    // TRUE - same as (bool)1 == TRUE
var_dump(1 === true);   // FALSE - same as (int)1 === FALSE
var_dump(0 == false);   // TRUE - same as (bool)0 == FALSE
var_dump(0 === false);  // FALSE - same as (int)0 === FALSE

The assignment operator "=" is used to assign a value to a variable. It is not used to compare!

Let's write some code!

Write a program that does the following:

  • Choose a number between 1 and 10 
  • Assign that number to the variable $x
  • Add five to $x
  • Double the result
  • Subtract 4
  • Divide by 2
  • Subtract the original number

Arrays

An array in PHP is an ordered map.

A map is a type that associates values to keys [10]

Think of arrays as dictionaries or directories. The names in the directory are keys that help you look up information faster, values

 

In an array the key is used to quickly look up for a value.

Example

<?php
// 06.arrays.php
$array = array(
    "foo" => "BAR",
    "bar" => "FOO",
);
print $array['foo'];  // bar

// as of PHP 5.4
$array = [
    "new" => "array",
    "syntax" => "use this",
];
print $array['syntax']; // use this

<?php 
// 06.arrays.php continued 

// if arrays are used without a key, 
// zero indexed numeric values are 
// assigned to them.
$array = ['apple', 'orange', 'banana'];
print $array[0]; // apple
print $array[1]; // orange
print $array[2]; // banana

Example Multidimensional

<?php
// 06.arrays.php

$array = array(
    "key" => "value",
    1     => 1234,
    "multi" => array(
        "another key" => "Another Value"
    )
);

It is possible to have an array of arrays

What are arrays good for?

Think of an array as a specialized way of organizing and storing data [11].  

PHP offers a wide range of functions to help you deal with arrays

What are arrays good for?

<?php
//07.arrays_menu.php

$menu = [
    'shake' => [
        'vanilla ice cream',
        'milk'
    ],
    'tiramisu' => [
        'instant-espresso powder',
        'sugar',
        '4 large egg',
        'heavy cream'
    ]
    'burger' => [
        'beef patty',
        'lettuce',
        'tomatoes',
        'buns'
    ],
];

ksort($menu);

print_r($menu);

Flow Control or Control Structures

So far we have created programs that have no logic, they follow a straight line. 

 

Control Structures are used to build logic into our programs.

Control Structures in PHP [12]

PHP supports several control structures but we will only look into the following:

  • If statements
  • Else statements
  • Elseif statements
  • For loops
  • Foreach loops

If Statements

If is a condition to check if something is true

<?php
// 08.if_statements.php

$number = 1;
if ($number === 1) {
    print "The number variable is equals to one.";
}

$string = "Foo Bar";
if (strpos($string, "Foo") !== false) {
    print "The string '$string' contains the word 'Foo'";
}

Else Statements

If you want to take an action If a condition is not met, use the else statement

<?php
// 09.else_statements.php

$number = 4;
if ($number === 1) {
    print "The number variable is equal to one.";
} else {
    print "The number variable IS NOT equal to one.";
}

$string = "Lala Bar";
if (strpos($string, "Foo") !== false) {
    print "The string '$string' contains the word 'Foo'";
} else {
    print "The word 'Foo' WAS NOT found in the string '$string'";
}

Elseif Statements

It is a combination of else and if. It is used to link multiple conditions.

<?php
// 10.elseif_statements.php

$number = 4;

if ($number === 1) {
    print "The number variable is equal to one.";
} elseif ($number === 2) {
    print "The number variable is equal to two.";
} elseif ($number === 3) {
    print "The number variable is equal to three.";
} else {
    print "I give up I don't know what the number is :(";
}

Loops

A loop allows us to repeat a piece of code many times. 

Each time we loop we can make small changes to our program in order to get a desired output.

Loops [13]

Imagine you want to print all the numbers from 1 to 10

<?php
// 11.for_loops.php

// with loops
for($i = 1; $i <= 10; $i++) {
    print "I'm using a loop, my current count is $i";
}
<?php
// 11.for_loops.php
// old way
print 1;
print 2;
// ...
print 10;

Expression 1 is executed once at the beginning of the loop

Expression 2 is evaluated on each iteration. The loop continues as long as the expression is true

Expression 3 is evaluated at the end of each iteration

Loops can be used to iterate over arrays

<?php
// 12.for_loops_fib.php
$fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
$size = sizeof($fib);

for($i = 0; $i < $size; $i++) {
    print $fib[$i];
}

// We can also create this same series 
// using simple math. 
$a = 1;
$b = 2;
print $a;
print $b;

for($i = 0; $i < $size-2; $i++) {
    $newB = $a+$b;
    $a = $b;
    $b = $newB;
    print $newB;
}

Foreach Loops

<?php
// 13.foreach_loops_fib.php
$fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89];

foreach($fib as $number) {
    print $number;
}

Foreach loops are meant to iterate over arrays or collections of objects

$numeros = ['uno' => 1, 'dos' => 2, 'tres' => 3];
// You can also get the key of the array
foreach ($numeros as $key => $value) {
    print "The key of the current 'numero' is $key and the value is $value";
}

First real application

Open the website directory. In there you will find several files. You only need to modify fibonacci.php and time.php

Open in the browser index.html

This file contains further information about this exercise

Display Time.

This website has a simple snipet of code written in JavaScript that will call two php files: time.php and fibonacci.php. You do not have to modify this file, just the PHP files.

Modify the time.php file to print the current time. Use the PHP Date Documentation to aid you with this task.

Fibonacci Series

Modify the fibonacci.php file to print a json encoded array with the current number and the previous number in the series up to 200 K, after that reset the series and start all over again. Use the PHP json_encode Documentation to print a json encoded array. You will find each number that you need in the super global $_GET['fib_1'] and $_GET['fib_2']

Conclusion

  • While you learn do not waste time setting up dev environments, use C9
  • PHP is a general purpose scripting language often used for the web
  • Variables are used to store data
  • Operators (assignment and arithmetic) are used to make transformations to the data
  • Comparison operators along with flow control statements are used to add logic to your programs
  • Loops enable you to run a piece of code multiple times making small changes to the program on each iteration.
  • Use foreach loops to iterate trough collections

References

questions?

THE END

Juan Manuel Torres | @onema

getting-started-with-php

By Juan Manuel Torres

getting-started-with-php

  • 2,466