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

Post on 13-Jan-2016

231 views 0 download

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

1

Lecture 5 – Function and Array

SFDV3011 – Advanced Web Development

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

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

4

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

the "call"

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)

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);

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.

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";

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)

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!

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

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

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?

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?

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()

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);

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";

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

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)

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

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

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]

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']}";

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).

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>';

?>

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>';

?>

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;}

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';

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>";

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?

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);

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).

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?

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?

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);