Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

35
Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1

Transcript of Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

Page 1: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

1

Lecture 5 – Function and Array

SFDV3011 – Advanced Web Development

Page 2: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

2

Functions A function is a named block of code (i.e. within

{}'s) that performs a specific set of statements– It acts on a set of values given to it

(parameters)– It may return a single value (return-value)

Functions are very useful for– Repeated tasks in multiple locations– Sharing useful code– Saving execution time– Modularization: Dividing up the task

Some functions are built in to PHP, some are added from code libraries, some you will define

Page 3: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

3

Calling a Function All PHP functions are designated by

<identifier>(<parameters>)• e.g. phpinfo(), rand(1,10)

Function names are not case sensitive

Full interface for a function:– <return type> <identifier>

( <parameters> )

identifier parameters

Page 4: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

4

Calling a Function Functions are used by calling them<?php … $commission = $sales * $rate; echo round($commission,2); … ?>

the "call"

Page 5: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

5

Passing Values into a Function: Parameters

Some Functions can be more flexible (therefore useful) if we pass them input values to use in their operations

Input values for functions are called passed values or parameters

Parameters must be specified inside the parentheses () of the function, and must be of the expected data type, in the expected order as defined by the function's interface

rand(int min, int max)

rand(1,10);

Parameter 1: min (int)

Parameter 2: max (int)

Page 6: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

6

Passing Variables Any legal expression can be used as a

parameter (recall that an expression returns a value)

rand(44%3, 2*$max*$max);

It is very common to use a variable for a parameter (recall: a variable by itself is an expression – it returns the value of the variable)

rand($minGuess,$maxGuess);substr($name,1,$i);

Page 7: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

7

Return Values of Functions Some Functions just perform an action (e.g. read

in a value from the keyboard, switch to a web page) and do not return a value

Most functions perform an action and return a single value

Return types may be:– a primitive data type, such as int, float, boolean, etc.– a compound type such as array, object, etc.– void if no value is returned

Return values are how a function passes information back after it is called and after it performs its operations.

Page 8: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

8

Return Values of Functions You can use a function with a returned value any

place where it is legal to use an expression, – $guess = rand(1,10);– 3.14159*rand(1,10); – echo phpinfo();– $yummy = "piece of " . substr("piece",0,3);– if( is_int($guess) ) …

A common return value for a function is boolean– true is the function operations were successful with no

problems– false if the function failed to perform its task

if( !writeFile() ) echo "file not written";

Page 9: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

9

Defining Functions

A very important aspect of PHP is the ability to create your own functions. You will find out how useful this is later.

You declare a function with the function keyword in front of a identifier and function parameter set and a code-block:

function <identifier> ( <parameters> ) {// function operations (code statements) here

return <expression> }

The way you define a function defines the functions interface (or how it is expected to be used)

Page 10: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

10

Function Syntax and Example

function funcname($var1, $var 2...)

{ statement 1; statement 2; statement 3; ... return $retval;}

function square($num){ $answer = $num * $num; return $answer;}

To call the function:$quantity = 3;$myvar = square

($quantity);

$myvar will contain the value 9

NOTE that the variable names do not need to be the same; the order of variables passed is what will matter inside the function!

Page 11: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

11

Global vs. Local Variables Variables defined inside a function (or passed in) are

"local variables" and are only available within functions– after exiting the function the variable ceases to exist!!!

Variables defined outside of a function are generally not available inside a function. So variables should be passed into a function as arguments!!!

Global variables are accessible both in and out of functions– NOT recommended!!! DON’T DO IT!!!!

Where the variable is active (alive) is known as its "scope"– use global and static to modify this– also "passing by reference" will affect scope

Page 12: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

12

Scope of Variables

Inside a function is like an entirely new program.

Variables that you define within the function have "local" scope:– They don't exist before the function

starts – They don't exist once the function has

completed

Page 13: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

13

Scope of Variables<?php

function deposit($amount){ $balance += $amount; echo "New balance is $balance

<BR>";}$balance = 600;deposit(50);echo "Balance is $balance";

?>

What will this

program print?

Why?

Page 14: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

14

Defining Functionsfunction swapTwoValues($a, $b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second}

$var1 = 1; $var2 = 2;echo "\$var1 is $var1 and \$var2 is $var2<BR>";

swapTwoValues($var1, $var2);echo "\$var1 is $var1 and \$var2 is $var2";

What would happen if we used $a and $b instead?

Page 15: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

15

Function Naming Conventions

Good Programming Practice (we will look for this!)• Use verbs to name functions that do not return

values or operate directly on variables– They usually perform an action e.g. sort(), print_table()

• Use nouns to name functions that return a value– they create (return) a piece of data, a thing e.g. date()

• Start function names with a lower case letter– phpinfo()

• Use "_" to separate words– is_bool()

• Use descriptive names– get_html_translation_table()

Page 16: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

16

Pass-By-Value vs. Pass-By-Reference

• When a function is called, the value of each argument is copied (assigned) and used locally within that function

• Variables used as arguments cannot be changed by a function!!!!!!!!!

• One way to change a value of a passed in variable is to make use of return value:function doubler($value) {

return 2*$value;

}

echo doubler($doubleUp);

$doubleUp = doubler($doubleUp);

Page 17: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

17

Pass-By-Value vs. Pass-By-Reference

• Sometimes it's more convenient to directly operate on a variable, so you pass in its reference (address):

function swapTwoValues(&$a, &$b) { $tmp = $a; // save old value temporarily $a = $b; // copy second parameter into first $b = $tmp; // copy original first value into second}$var1 = 1; $var2 = 2;echo "\$var1 is $var1 and \$var2 is $var2<BR>";swapTwoValues($var1, $var2);echo "\$var1 is $var1 and \$var2 is $var2";

Page 18: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

18

Arrays• A general kind of ordered collection.• Special features:

– Built-in to PHP, has special syntax.– Elements can be any type of data

(including other arrays!)– Arrays may indexed or associative (or

both!)– All arrays in PHP are associative

• Keys are automatically set to integers if you don’t specify them

Page 19: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

19

ArraysDefinition: An array is a named collection of

valuesvalue 17 'Hi' 9.33 NULL true

0 1 2 3 4element position(identified by index)

$indexedArray

value 17 'Hi' 9.33 NULL true

'age' 'greet' 'amount' 'notset' 'is_easy'

$associativeArray

element position(identified by key)

Page 20: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

20

Some Array Terminology

$product['price']

$product['price']

$product['price']

$product['price'] = 32;

Array name

key - also called a subscript - must be an int, - or an expression that evaluates to an int

keyed variable - also called an element or subscripted variable

Note that "element" may refer to either a single indexed variable in the array or the

value of a single indexed variable.

Value of the indexed variable; also called an element of the array

Page 21: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

21

Some Array Terminology (indexed)

$temperature[$n + 2]

$temperature[$n + 2]

$temperature[$n + 2]

$temperature[$n + 2] = 32;

Array name

Index - also called a subscript - must be an int, - or an expression that evaluates to an int

Indexed variable - also called an element or subscripted variable

Note that "element" may refer to either a single indexed variable in the array or the

value of a single indexed variable.

Value of the indexed variable; also called an element of the array

Page 22: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

22

Subscripting

• Principal feature of arrays: ability to access each element easily. Use notation

to access elements of an array. – If the key-expression has integer value n,

this returns the n'th element in array-name, counting from zero (!)

– If the key-expression is a string, it returns the value associated with that key

array-name[key-expression]

Page 23: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

23

Subscript Errors• Using a subscript larger than length-1 or

less than 0 or a key that does not exist will not cause the program to stop executing.– No element will be returned– Take care to use the correct subscripts!

• Be careful of interpolation problems when accessing array elements within a string

echo "The product is $product['name']"; // won't work!echo "The product is $product[name]";echo "The product is {$product['name']}";

Page 24: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

24

Finding the Length of an Array

• Size of $anArray can be determined using count($anArray) or sizeof($anArray).

• This is useful when using an array of unknown size in a loop:$counter=0;while( $count < sizeof($anArray) ) { echo "element $counter is {$anArray[$counter]}"; $counter++; }

How big is $anArray? We don’t need to know!Just use count($anArray)or sizeof($anArray).

Page 25: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

25

Echoing HTML

<?phpecho '<b><i>Hello World!!!!</b></i><br>';echo '<hr>';echo '<table border = 1>

<th>Column 1</th> <th>Column 2</th> <tr> <td>Hello Class</td> <td>Hello Again</td> </table>';

?>

Page 26: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

26

Generating HTML with Loops

<?php $users = array('Jason', 'Phil', 'Herbert', 'Anil');

echo '<center>';echo '<table border = 2 >';

echo '<th>Number</th><th>Username</th>';

for ($i = 0; $i < count($users); $i++){

echo '<tr>'; echo "<td>$i</td>"; echo "<td>$users[$i]</td>"; echo '</tr>';

}echo '</table>';

?>

Page 27: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

27

Simple Array Processing• Arrays can be processed using

iteration. Standard array-processing loop:

• What about associative arrays?

for ($i=0; $i < count($angles); $i++) { print "angle $i: ". $angles[$i];}

foreach ($products as $key => $value) { print 'key ' . $key . ' has value ' $value;}

Page 28: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

28

Multi-dimensional Arrays• Arrays can hold any PHP data type

including other arrays• This is useful for creating multi-

dimensional arrays$row1 = array('a','b','c');$row2 = array('d','e','f');$row3 = array('g','h','i');// make 2-dim array of rows$matrix = array($row1, $row2, $row3);

echo $matrix[0][0];echo $matrix[1][2];echo $matrix[2][1];$matrix[2][2] = 'I';

Page 29: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

29

Multi-dimensional Arrays• There's no reason you cannot mix

indexed and associative arrays (you will find this useful later)

$product1 = array('name' => 'small gumball', 'price' => 0.02);$product2 = array('name' => 'medium gumball', 'price' => 0.05);$product3 = array('name' => 'large gumball', 'price' => 0.07);

// array of all products$products = array($product1, $product2, $product3);

for($i=0; $i<count($products); $i++) echo "Product: $i is {$products[$i]['name']} and costs {$products[$i]['price']} each<br>";

Page 30: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

30

Element Existence

• Sometimes it's useful to know an element exists in an array. Use the array_key_exists() function for this:

$product = array('name' => 'small gumball', 'filling' => NULL, 'price' => 0.04);if( array_key_exists('name', $product) )

echo "Product is {$product['name']}";

• Why not just use isset()?

array_key_exists('filling', $product) // returns?

isset($product['filling']) // returns?

Page 31: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

31

Searching

• You can test for an element in array with in_array()

if (in_array('small gumball', $product))

print('we sell small gumballs');

• You can search for an element key by value in an array with array_search()

print "the key for small gumball is " . array_search('small gumball', $product);

Page 32: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

32

Sorting

There are many ways to sort the elements in array such as sort(),asort(),ksort():

$a = array('3', 'a', 'c', 'b', '2', '1');sort($a);

– Take care with sorting functions as they do not return the sorted array. The array is directly manipulated (the parameter is passed by reference).

Page 33: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

33

Keys and Values$product = array('name' => 'small gumball', 'filling' =>

'solid', 'price' => 0.04);

• Use array_keys() to get an array of an array's keys

$prodKeys = array_keys($product);

• Use array_values() to get an array of an array's values

$prodValues = array_values($product);

• When would you want to use either of these?

Page 34: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

34

Removing and Inserting Elements

$product = array('small gumball','solid', 0.04);

• Usually you will simply create a new array if you need to insert or remove elements

$prodNoFilling = array($product[0], $product[2]);

• You can use array_splice() to insert or remove elements directly

array_splice($product, 1, 1); // removes elem 1array_splice($product, 1, 1, 'hollow'); // replaces elem 1array_splice($product, 1, 0, 'logo'); // inserts at elem 1

Challenge: What happens to $product if you executed the above as is?

Page 35: Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.

35

Array functions$nums1 = array(1,2,3,4,5, 5.0);$nums2 = array(5,6,7,8,9);

• Merging arrays – splices together$mergeNums = array_merge($nums1, $nums2);

• Array Unique – all unique values (uses ==)$unionNums = array_unique($nums1);

• Array Intersection – all common values (uses ==)

$intsctNums = array_intersect($nums1, $nums2);

• Array Difference – return all values of $nums1 that are not in $nums2

$diffNums = array_diff($nums1, $nums2);