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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Arrays.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Objectives Using functions to organize PHP code
ITC 240: Web Application Programming
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Java Unit 9: Arrays Declaring and Processing Arrays.
Python quick start guide
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
INTERNET APPLICATION DEVELOPMENT For More visit:
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Chapter 8 Arrays and Strings
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Scope When we create variables and functions, they are limited in where they are visible and where they can be referenced For the most part, the identifiers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
JavaScript, Fourth Edition
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
ITM ITM 352 Array Processing. ITM Simple Array Processing  Arrays can be processed using iteration. Standard array-processing loop:  What.
ITM © Port, Kazman1 ITM 352 Simple Arrays. ITM © Port, Kazman2 Arrays r Collections r Array basics m Declaration, allocation, and initialization.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
CSE 154 LECTURE 15: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Arrays Chapter 7.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 3 OF 3
Introduction to C++ Systems Programming.
JavaScript: Functions.
User-Defined Functions
Arrays, For loop While loop Do while loop
PHP.
Object Oriented Programming in java
Arrays Chapter 7.
ITM 352 Simple Arrays.
ITM 352 Array Processing.
Web Programming and Design
ITM 352 Functions.
Presentation transcript:

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

3 Calling a Function  All PHP functions are designated by ( ) e.g. phpinfo(), rand(1,10)  Function names are not case sensitive  Full interface for a function: – ( ) 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); – *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 ( ) { // function operations (code statements) here return }  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 "; } $balance = 600; deposit(50); echo "Balance is $balance"; ?> What will this program print? Why?

14 Defining Functions 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 "; 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 "; 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 Arrays Definition: An array is a named collection of values value 17 'Hi' 9.33 NULL true element 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'] = 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] = 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 <?php echo ' Hello World!!!! '; echo ' '; echo ' Column 1 Column 2 Hello Class Hello Again '; ?>

26 Generating HTML with Loops <?php $users = array('Jason', 'Phil', 'Herbert', 'Anil'); echo ' '; echo ' Number Username '; for ($i = 0; $i < count($users); $i++) { echo ' '; echo " $i "; echo " $users[$i] "; echo ' '; } echo ' '; ?>

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

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 1 array_splice($product, 1, 1, 'hollow'); // replaces elem 1 array_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);