Introduction to

programming

April 2019 

By Loïc TRUCHOT

Featuring PHP

The perfect stack

for a 2019 web programmer

  • PHP / MySQL (+ Laravel, Zend or Symphony...)
  • Node.js / MongoDB
  • Wordpress
  • HTML
  • CSS (+ SASS)
  • JavaScript (+ React, Angular or Vue...)

Bonus : Bootstrap, JQuery

About PHP

  • Very classic
  • Server-side language to produce dynamic website
  • Paradigm: Procedural (imperative) + Object Oriented
  • Interpreted when page is asked (not compiled before)
  • 80% of the web 
    • Facebook, Dailymotion, Wikipedia, WordPress, Slack...
  • Current version: 7.4
  • What does PHP do finally ?
    • It generate HTML page with
      • dynamic parts, changing for each user, content, URL
      • static parts, reusing all common contents, like headers, footers, left menu...
      • server operation (calcul, database, CRUD, sessions, API...)

Install & run PHP

  • As any language, PHP must be installed
  • As any webserver, PHP should ran in background
  • 3 alternatives: EasyPHP, Wamp, Xampp
  • Let's try EasyPHP, the simplest...
    • https://www.easyphp.org
    • download the 17.0 DevServer for Windows 10
    • install it (as administrator if needed), say "yes" and "next" to everything
    • run, and find the            logo in your main status bar

Use the REPL

  • open the dashboard
  • PHP code tester: a Read-Eval-Print Loop
  • click "interpret", then describe what you see
  • clean the PHP code tester
  • add a <h1></h1>, name your Pizzeria here
  • add a <h2></h2>, say "hello" to your neighbor here

  • click "Interpret" button

Variables

  • What is "variable" here ?
  • Let's add this new code (now, never press "stop" again)
  • replace first variable with <?php echo 'variable'; ?>
  • click "Interpret" button
<h1>Pizza YOLO</h1>
<h2>Hello Sonia !</h2>
<p>
    Today is friday: week-end is coming.<br />
    What about a delicious Pizza tonight, Sonia ?
</p>
<div>
    Try our classics :
    <ul>
        <li>Vegeteriana</li>
        <li>Il Diavolo</li>
        <li>Quattro Formagi</li>
    </ul>
    Or choose the daily chef choice:
    <strong>the Calzone</strong>
</div>
<p>
    <em>Pizza price: 10 € - See you soon Sonia.</em>
</p>

step 1

Variables

  • declare the $name variable
  • Assign it the value "Sonia"
  • replace the "Sonia" part, after echo, with your own variable
  • click "Interpret" button
<?php 
    $name;
?>
<h1>Pizza YOLO</h1>
<h2>Hello <?php echo "Sonia"; ?> !</h2>

step 2

To remember

  • PHP code is mixed with the HTML
  • The PHP markup is <?php ... ?>
  • echo is a PHP function that "print" anything in the HTML
  • a PHP variable begin with the sign "$", like in $myVar
  • a PHP statement always end with a ";"
  • a variable assignment is done with the "="
  • full exemple :
<?php 
    $name = "Sonia";
?>
<h1>Pizza YOLO</h1>
<h2>Hello <?php echo $name ?> !</h2>

Let's migrate to

a real file index.php

 

  • Copy contents to an index.php file
  • Create a folder for your project (without accents or whitespaces, like C:\php\pizza), put your file inside
  • Stop the REPL
  • Add your folder as working dir in EasyPHP dashboard
  • Start the HTTP Server, click the link-name of your project
  • Let's examine the result
  • Use sublime-text / vs-code to open the folder
  • Do some change in index.php, then press [F5]

Workshop session

variables

  • Open index.php with Sublime Text / VS Code
  • Replace every variables texts with some new variables like $name

Variables

  • string -> concatenations
<?php 
    $firstname = "Samir";
    $lastname = "Hanini";
?>
<h1>Pizza YOLO</h1>
<h2>Hello <?php echo $firstname; ?> !</h2>

step 3

Types

  • Integer or Float -> calculations
<?php 
    $nbOfPizza = 5;
    $price = 10;
    $discount = 0.2;
?>
<strong>Total: </strong>
  • boolean -> conditions
<?php
    $isConnected = true;
    $hasDiscount = true;
?>
<strong>Is connected and has discount : </strong>

To remember

  • A variable is useful for :
    • replace part of the page that can change (ex: a name)
    • store repeated pattern (ex: an info displayed 3 times)
    • store temporary needed value (ex: a discount multiplier)
  • A variable is like a box, we can change what is inside
    • $price = 10;
      • before " = ", the left part is the box
      • after " = ", the right part is the new value we put inside
  • When PHP is interpreted, right part variables are evaluated, replaced by its value
    • $price = $price * 3 + $price;
      • $price value is now  40
  • Each value have a "type" (string, number, boolean, etc)
  • Each type has different operations (concat, add, compare, etc)

Control structures

Logical conditions

  • if (boolean) { thenDoThis( ); }
  • else { otherwiseDoThat(); }
  • Operators: &&, ||, <, <=, >, >=, ==, !=, !
  • elseif, for multiple possibilities
  • Coercion: 0, "", null...
  • ,
<?php 
    $name;
?>
<h1>PHPizza</h1>
<?php 
    if (isset($name)) {
        echo "<h2>Hello $name !</h2>";
    } else { 
        echo "Please, <button>log in</button>";
    }
?>

step 1

Workshop session

if else

  • Apply different discount to total 
    • not set -> nothing
    • less than 20€ -> nothing
    • between 20€ & 30€ -> 10%
    • between 31€ & 50€ -> 20%
    • more than 50€ -> 30%

Logical conditions

  • switch ($var) { }
  • list every possibilities:
    • case "value 1":
      • doThis();
      • break;
    • case "value 2":
      • doThat();
      • break; 
  • add default possibility:
    • default:
      • doDefault();
<?php 
    $discountCode = "abc"; 
    $isLogin = false;
    $name;
    echo "<header>Hello "  
        . ($isLogin ? $name : "you") 
        . "</header>";
    switch ($discountCode) {
        case "abc":
            echo "10€ de réduction";
            break;
        case "def":
            echo "20€ de réduction";
            break;
        default:
            echo "Pas de réduction";
    }
?>

step 2

  • Ternary :
    • true ? whenTrue(); : whenFalse();

Workshop session

switch

  • Apply a different discount for 4 differents codes
  • If no discount code, apply 1€ discount
  • In all case, minimal price is  10€ (use ternary condition)

To remember

  • if / else is the basic block of any computer program
  • It needs a boolean, or anything convertible to boolean
  • A shorter way exists : the ternary operator, x ? a : b;
  • elseif for extra conditions
  • first condition fullfilled is the one
  • switch for several values of the same var

Loops

  • A recursive "if"
  • Do it until something becomes false: "while (boolean) { }"
  • Why some loop can freeze the computer ?
<?php 
$x = 1; 

while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
} 
?>

step 1

Workshop session

while

  • Create a loop for our working pizzaïolos
    • it display x times "A new pizza was just bought."
    • after half times reached, it says "Keep going: half done !"

Loops

  • the for loop, with start & end conditions 
  • for (start; condition; operation) { }
  • The most popular : force to think to the ending condition
<?php 
    for($x = 1; $x <= 5; $x++) {
        echo "The number is: $x <br>";   
    } 
?>

step 2

Workshop session

for

  • rand(1, 100) return an integer between 1 and 100
  • our curstomers have 30% chance to win a discount
  • generate 100 draws, and display win & lose in a <ul>

To remember

  • while is the classical loop: work like a if, but repeated until condition is false
  • so you MUST think about the end of the loop
  • that's why for loop is mostly used: start, end, change are described directly
  • rand(x, y); is a PHP function to get a random number

To finally remember

  • A computer can :
    • store / memoize (variables)
    • calculate / combine (operations)
    • compare (conditions)
    • repeat / iterate  (loops)

Refacto time

  • comment your code with // and /* */
  • put everything in a proper HTML doc
  • add bootstrap and some prettier classes

Data structures

Array

  • array = super variable containing several elements, like a shelf of boxes
  • So it's a list of data
    • $list1 = array(4, 8, 15, 16, 23, 42);
    • $list2 = array("Samir",  "Sarah", "Jordan", "Anaïs");
  • Each data is indexed from 0 to n
  • We can access any "box" by its [index]
  • count($myArray) return the length of my array
<?php 
    $list = array("Pascal", 45, "Coach", false, "Amsterdam"); 
    echo "His name is " . $list[0] .", he live in ". $list[4];
?>

step 1

Workshop session

array

  • Put our list of pizza in an array
  • Iterate with a for loop, to display all pizzas in the <ul>
  • pick a random pizza as a daily choice

Array

  • A new loop: the foreach
  • With or without index
<?php 
$birds = array("cardinal", "kestrel", "kite", "mockingbird"); 

foreach($birds as $bird) {
    echo $bird . " says tweet tweet.<br />";
}
shuffle($birds);
foreach($birds as $index => $bird) {
    echo $bird . " is now n°" . $index . " in the list<br />";
}
?>

step 2

  • What about array of arrays ? no problem, as much as you need
  • And so on ??? It's just multidimensional arrays / matrix

Workshop session

array

  • Put your old pizzas array as first element of a new "food" array
  • Add an array of drinks, and an array of desserts in this food array
  • Display everything in <ul> with nested foreach loops
  • Display a title before each <ul>: Pizzas, Drinks, Desserts

PHP array functions

  • Remember the CRUD ? 
    • Create: array_push($list, "element3", "element4");
    • Read: echo $list[2];
    • Update: $list[2] = "new element";
    • Delete: array_splice($list, 2, 1)
  • Some other useful tools:
    • array_unshift ()
    • count()
    • sort(), shuffle(), array_reverse()
    • array_sum()
    • @see further doc when you have an idea
      • https://www.php.net/manual/en/ref.array.php

hashtables 

  • Just like an array, but indexed by string
  • Unordered, but well organized
  • Crucial in Oriented Object Programming
  • foreach becomes handy
<?php 
    $person = array(
        "name" => "Pascal", 
        "age" => 45, 
        "job" => "Coach", 
        "married" => false, 
        'city' => "Amsterdam"); 
    echo "His name is " . $person["name"] .", he live in ". $person["city"];
    foreach($person as $key => $value) {
        echo "$key: $value</br>";
    }
?>

step 1

Text

Text

Text

  • keyed list, associative list, dictionary...
  • very similar to objects

hashtables

  • One of the most common data structure: the collection
  • Collection = array of hashtables, all formatted the same way
  • Just like in an excel...
  • Just like in a data base !
<?php 
    $person = array(
        array("first" => "Nicolas", "last" => "Cage"),
        array("first" => "John", "last" => "Travolta"),
    ); 

    foreach($person as $value) {
        echo $value["first"] . " " . $value["last"] . "</br>";
    }
?>

step 2

Workshop session

hashtables

  • Create a pizza object for the "vegetariana" with
    • a name
    • a description
    • a list of ingredients
    • a price
    • an image (find it on Internet !)
  • Do the same for each pizzas, and put them in a collection
  • Change website code: it should work with this collection

To remember

  • Data stucture is: "how to store logically and efficiently my data ?"
  • Variables of primitives (string, boolean, number) ? Array ? Hashtables ? Collections (array of hashtables ?)
  • With PHP
    • declaring a new array:
      • $list = array(1, 2, 3);
    • declaring a new hashtable:
      • $object = array("a" => 1, "b" => 2);
  • In all case, use foreach to loop on it

Functions

  • The most important thing in computer science...
  • ...in a  human point of view
  • Reusable routine/subprogram
  • Something already existing, or something I'll build myself
  • Something I can bring with me all my programmer life
  • declaration != execution
<?php
    // declaration (nothing happen)
    function say_hello () {
        echo "hello<br/>";
    }
    // execute 2 times (write "hello<br/>" 2 times)
    say_hello();
    say_hello();
?>

step 1

Functions

  • A function can (should ?) :
    • get some parameters (arguments)
    • return something 
    • it's an input -> output reusable process
<?php 
    function add($a, $b) {
        return $a + $b;
    }
    echo add(3, 5);
    echo add(198708, 12349);
?>

step 2

Functions

  • The "return" keyword imply the end of the function
function checkToDo($isDone) {
    if ($isDone == true) { 
        return "the task is done.";
    } else {
        return "the task is not done.";
    }
    // following statement will never be evaluated
    echo "this will not happen";
}

step 3

  • No return function ? it will return NULL at the end: it's a special empty value
function test ($a) {
    $b = $a * 2;
    // nothing returned ?
}
echo (test(42) == NULL); // will be TRUE and log "1"

Workshop session

functions

  • Write a function that return the average age in the classroom
  • Use "round" to format this number

Workshop session

functions

  • Write a function that return a "card" for each pizza
  • Pizza can only have 2 types of meat: chicken and ham
  • If the pizza is vegetarian, it must appear in the card

Live coding session

bigger functions

Write a function that can perform some quizz

$quizz = array(
    array("q" => "Hélium", "a" => "He"),
    array("q" => "Oxygène", "a" => "O"),
    // and at least 2 more similar Question/Answer 
);
  • return a hashtable with
    • a random question
    • 4 shuffled answers, 3 random + the right one
    • the index of the right answer
  • take a quizz as param

Digression about

value VS reference

Functions

  • Pure functions = predictible
    • any input always generate the same output
function add2 ($n) {
    return $n + 2;
}
add2(2);
add2(2);

step 6

  • Impure functions = side effects
    • done with & near params, the "reference mark"
    • can change something in another part of the program
$age = 33;
function happyBirthday (&$n) {
    $n = $n + 1;
}
happyBirthday($age);
happyBirthday($age);
echo $age;
  • Try this code with and without & to see the difference !

To remember

  • Procedural languages are only about
    • data stuctures  (vars, arrays) and types
    • control structures (if, for, foreach)
    • functions
      • pures (predictible input -> ouput)
      • impures (side effects)
  • Oriented Object languages like PHP have more complexity:
    • classes and instances
  • Functional languages like Haskell have less complexity:
    • ​no control structures (replaced by functions)
    • only pures functions

THANKS EVERYONE
It's finally done !

 

 

 

 

 

 

See you soon with a "Deeper PHP" module

  • Multiple files projects
  • Oriented Object PHP
  • PDO classe and DataBase CRUD
  • AJAX and Forms treatment

Introduction to programming 2019

By Loïc TRUCHOT

Introduction to programming 2019

Discovering computer science basis with some PHP examples

  • 296