CSE 154

Lecture 17: PHP Arrays, Functions, and GET/POST

Administrivia

Reminder that HW3 Milestone 1 is due tonight:

  • TA's have been hard at work to provide HW2 feedback, but we won't be able to get this published by tonight - they have put together a list of common issues on Piazza we highly recommend reviewing before submitting!
  • There is a very helpful demo video for HW3 up! Use it for reference when working on HW3 and to check that you've handled edge cases before submitting

If you need left-handed seating for the Final, please fill out the survey on the course home page (announcements) page by Wednesday!

Exploration session this week on websockets!

Notecard Feedback

We have been working on incorporating some very useful suggestions from "Gots" and "Needs"!

Gots

  • "Creative projects have been really helpful to explore new features in HTML/CSS/JS and getting feedback before HW - it's been helpful to have modules to know where to focus"
  • "More experience reading and following code project specifications"
  • "It was helpful to start HW2 early, and I found it the most useful thing to connect what we've learned with HTML, CSS, and JavaScript."
  • "Understanding the different components of JS, such as event listeners, query selectors, and timers"
  • "CodeStepByStep problems have been useful for practicing new topics and preparing for the exam"
  • "How to cite sources in web pages"
  • "Getting better at debugging in the browser"

Needs

  • "Style guide is frustrating" - let us know why this is the case. We've heard the style guide is also very useful to have.
  • "More examples of common bugs when learning new languages" - we are working on a "Common PHP Bugs" document with examples and tips on how to debug PHP programs!
  • "There was too much of a jump in difficuty from HW1 and HW2" - the milestone for HW3 seems to be helping - we will incorporate this feedback in Spring.
  • "More practice problems" - we have added more interactive language tutorials under "Extra Resources" for students wanting more practice, as well as CSBS exercises for JS/PHP! We will also have extra problems in section/lab this week for you to practice at home if you'd like.
  • "More resources" - please make sure you are using the many resources we have offered this quarter (readings, practice exercises, Piazza, etc.). Utilize WPL and OH if you haven't! These are some of the best resources students aren't taking advantage of.
  • "More advanced JS features" - we are happy to provide resources, but we already cover a lot in this course - CP's are an excellent way to explore though!

Back to PHP: Today's Agenda

Wrapping up PHP Syntax

Accessing GET/POST parameters in PHP

Lecture Warmup

<?php
  header("Content-type: text/plain");
  $course = "CSE154";
  $month = "November";
  $abbr = $month.substr(0, 3);
  $yesterday = "4";

  echo "Hello {$course} student!";
  echo "It's Monday, $abbr." + ($yesterday + 1) + "th!";
?php>

(Buggy) PHP

What bugs did you find?

Lecture Warmup Solution

<?php
  header("Content-type: text/plain");
  $course = "CSE154";
  $month = "November";
  $abbr = substr($month, 0, 3);
  $yesterday = "4";

  echo "Hello {$course} student!\n";
  echo "It's Monday, {$abbr}. " . ($yesterday + 1) . "th!";
?>

PHP

For Loops

for (initialization; condition; update) {
  statements
}

PHP (template)

for ($i = 0; $i < 10; $i++) {
  echo "$i squared is " . $i * $i . "\n";
}

PHP (example)

(remember . not + for string concatenation)

PHP vs. JavaScript vs. Java

for ($i = 0; $i < 10; $i++) {
  echo "$i squared is " . $i * $i . "\n";
}

PHP

for (let i = 0; i < 10; i++) {
  console.log(i + " squared is " + (i * i));
}

JS

for (int i = 0; i < 10; i++) {
  System.out.println(i + " squared is " + (i * i));
}

Java

If/Else Statements

if (condition) {
  statements;
} else if (condition) {
  statements;
} else {
  statements;
}

PHP (template)

While Loop (same as Java/JS)

while (condition) {
  statements;
}

PHP (template)

do {
  statements;
} while (condition);

PHP (template)

break and continue keywords also behave as in Java (do not use these in this course)

Functions

function name(parameterName, ..., parameterName) {
  statements;
}

PHP (template)

function item_cost($qty, $unit_cost, $tax) {
  $total_cost = $qty * $unit_cost;     # e.g. 4 * 1.25 = 6.00
  $tax_amount = $total_cost * $tax;    # e.g. 6.00 * 0.1 = 0.60
  $result = $total_cost + $tax_amount; # e.g. 6.00 + 0.6 = 6.60
  return $result;
}

PHP (example)

Very similar to JavaScript functions!

  • Parameter types and return types are not written
  • A function with no return statements is implicitly "void"

Calling Functions

name(expression, ..., expression);

PHP (template)

$qty = 4; 
$cost = 1.25; 
$total = item_cost($qty, $cost, 0.10);

PHP (example)

  • If the wrong number of parameters are passed, it's an error

Arrays

$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index]          # get element value
$name[index] = value; # set element value
$name[] = value;      # append value

PHP

$a = array();             # empty array (length 0)
$a[0] = 23;                       # stores 23 at index 0 (length 1)
$drinks = array("coffee", "tea", "water");
$drinks[] = "hot cocoa";          # add "hot cocoa" to end (at index 3)
array_push($drinks, "hot cocoa"); # identical to above line

PHP

  • Two alternative ways to append:
    1. Use bracket notation without specifying an index
    2. Use array_push(arr, value)
  • Array element type is not specified; can mix types (but generally shouldn't)

PHP vs. JS vs. Java

$a = array(); # empty array (length 0)
$a[0] = 23;                       # stores 23 at index 0 (length 1)
$drinks = array("coffee", "tea", "water");
$drinks[] = "hot cocoa";          # add "hot cocoa" to end (at index 3) 
$drink_count = count($drinks);    # 4 

PHP

let a = []; 
a[0] = 23;                        
let drinks = ["coffee", "tea", "water"];
drinks[] = "hot cocoa";          
let drinkCount = drinks.length; 

JS

int[] a = new int[1]; // need length when creating array in Java!
a[0] = 23;                       
String[] drinks = new String[]{"coffee", "tea", "water", ""};
drinks[3] = "hot cocoa";         
int drinkCount = drinks.length;

Java

Exercise: Writing a to_string function for arrays

Write a PHP function to_string which takes an array as a parameter and returns a comma-separated, bracketed string representation.

For example, if the following array is defined:

$drinks = array(“coffee”, “tea”, “water”);
        

The call to_string($drinks) should return the string "[coffee, tea, water]".

to_string Solution

One solution is given below:

function to_string($arr) {
  $result = "[";
  for ($i = 0; $i < count($arr) - 1; $i++) {
    $result .= $arr[$i] . ", ";
  }
  if (count($arr) > 0) {
    $result .= $arr[count($arr) - 1];
  }
  return $result . "]";
}

PHP

Working example in menu.php (from php-examples-ii.zip

Array Functions

Function name(s) Description
count number of elements in the array
print_r print array's contents
array_pop, array_push, array_shift, array_unshift using an array as a stack/queue
in_array, array_search, array_reverse sort, rsort, shuffle searching and reordering
array_fill, array_merge, array_intersect, array_diff, array_slice, range creating, filling, filtering
array_sum, array_product, array_unique, array_filter, array_reduce processing elements

Array Function Example

$langs = array("HTML", "CSS", "JS", "PHP");
for ($i = 0; i < count($initials); $i++) {
  $langs[$i] = strtolower($langs[$i]);
} # ("html", "css", "js", "php")

$html = array_shift($langs);   # ("css", "js", "php")
array_pop($langs);             # ("css", "js")
array_push($langs, "html");    # ("css", "js", "html")
array_reverse($langs);         # ("html", "js", "css")
sort($langs);                  # ("css", "html", "js")
$html2 = array_slice($langs, 1, 2); # ("css", "js")

PHP

The array in PHP replaces many other data structures in Java

  • e.g. list, stack, queue, set, map, ...

Review: GET and POST

There are two common ways to make AJAX requests to a server.

  • GET requests are intended to get information from the server (this is the default, most of what you've seen uses GET requests).
  • POST requests are intended to send information to the server, often changing information on the server.

Query Parameters in PHP

  • PHP includes built-in arrays to hold GET and POST parameters called $_GET and $_POST
  • To can access these parameters by putting the parameter name as a string index for the GET/POST array.
  • For example, to access a GET parameter name, reference it in PHP as $_GET["name"]
  • If it were instead passed as a POST parameter (e.g. through FormData with fetch) you would access it in PHP with $_POST["name"]
  • Most of the web services you will write in this class will accept GET parameters, but when we start using PHP to update files/databases, we will use POST requests to modify this data on the server.

Example of GET in PHP

For a GET url with parameters passed, like:
hello.php?name=mowgli&age=2

<?php
  $name = $_GET["name"];
  $age = (int) $_GET["age"];
  $dog_age = $age * 7;
  echo "Hi {$name}! You are {$age} years old!\n";
  echo "That's {$dog_age} in dog years!";
?>

PHP

A Basic Greeter PHP Web Service

greeter.php?name=Mowgli

hello.html (a simple webpage using hello.js to fetch from greeter.php using a GET request). You can practice updating these examples from php-examples-ii.zip!

Example of POST in PHP

For a POST to url with parameters passed, like:

let url = ..... // put url string here
let data =  new FormData();
data.append("username", "Kyle");
data.append("password", "cse!54webz");
data.append("word", "duck");
data.append("definition", "a debugger friend");
fetch(url, {method: "POST", body: data})
...

JS

PHP Code:

$username = $_POST["username"];
$password = $_POST["password"];
$users_pw_hash = db_lookup_hashed_pw($username);

if (password_hash($password) == $users_pw_hash) {
  print("Successfully logged in!");
  // code to update word/definition to a file on the server
}

PHP