Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals.

Similar presentations


Presentation on theme: "CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals."— Presentation transcript:

1 CSCI 116 Week 3 Functions & Control Structures

2 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals Decision logic Decision logic if statementsif statements if...else statementsif...else statements switch statementsswitch statements Loops Loops while statementswhile statements do...while statementsdo...while statements for and foreach statementsfor and foreach statements

3 3 Defining Functions Functions Functions Groups of statements that you can execute as a single unitGroups of statements that you can execute as a single unit Defining a function : Defining a function :<?php function name_of_function(parameters) { statements; statements;}?>

4 4 Function Parameters A parameter is an input to the function A parameter is an input to the function Parameters are placed within the parentheses that follow the function name Parameters are placed within the parentheses that follow the function name Not all functions accept parameters Not all functions accept parameters function average($num1, $num2) function printHello() function calcTax($price) 2 parameters 0 parameters 1 parameter

5 5 Function Example function printPhrase($phrase) { echo “$phrase ”; } printPhrase(“Silly goose!”);

6 6 Returning Values A return statement returns a value to the statement that called the function A return statement returns a value to the statement that called the function A function does not have to return a value A function does not have to return a value function averageNumbers($a, $b, $c) { $sumOfNumbers = $a + $b + $c; $average = $sumOfNumbers / 3; return $average; }

7 7 Function Practice 1. Write a function that takes a name and prints “Hello, name!” 2. Write a function that returns the maximum of two values. 3. Write a function that converts celsius to fahrenheit (F=C*1.8+32). 4. Write a function that takes a radius and returns the circumference of a circle (C=PI*Diameter).

8 8 Understanding Variable Scope Variable scope Variable scope Where in your program a declared variable can be usedWhere in your program a declared variable can be used Can be either global or localCan be either global or local Global variable Global variable Declared outside a function and available to all parts of your programDeclared outside a function and available to all parts of your program Local variable Local variable Declared inside a function and only available within that functionDeclared inside a function and only available within that function

9 9 Variable Scope <?php $globalVar = "Global"; function scopeExample() { echo " Inside function: "; $localVar = "Local"; echo "$localVar "; global $globalVar; echo "$globalVar "; }scopeExample(); echo " Outside function: "; echo "$localVar "; echo "$globalVar "; ?> global keyword used inside function to reference global variable

10 10 Autoglobals PHP includes predefined global arrays, called autoglobals or superglobals PHP includes predefined global arrays, called autoglobals or superglobals Autoglobals contain client, server, and environment information Autoglobals contain client, server, and environment information Autoglobals are associative arrays Autoglobals are associative arrays Elements are referred to with an alphanumeric key instead of an index numberElements are referred to with an alphanumeric key instead of an index number Example: $_SERVER[“PHP_SELF”]Example: $_SERVER[“PHP_SELF”]

11 11 PHP Autoglobals See http://us.php.net/reserved.variables for more information.http://us.php.net/reserved.variables

12 12 Using $GLOBALS <?php $globalVar = "Global"; function scopeExample() { echo " Inside function: "; $localVar = "Local"; echo "$localVar "; echo $GLOBALS["globalVar"], " "; } scopeExample(); echo " Outside function: "; echo "$localVar "; echo "$globalVar "; ?>

13 13 Using $_SERVER <?php echo "The name of the current script is ", $_SERVER["PHP_SELF"], " "; echo "The absolute path of the current script is: ", $_SERVER["SCRIPT_FILENAME"], " "; echo "The name of the server on which this script is executing is: ", $_SERVER["SERVER_NAME"], " "; echo "This script was executed with the following server software: ", $_SERVER["SERVER_SOFTWARE"], " "; echo "This script was executed with the following server protocol: ", $_SERVER["SERVER_PROTOCOL"]; ?>

14 14 Using $_GET and $_POST $_GET and $_POST allow you to access the values of forms that are submitted to a PHP script $_GET and $_POST allow you to access the values of forms that are submitted to a PHP script $_GET appends form data as one long string to the URL $_GET appends form data as one long string to the URL $_POST sends form data as a transmission separate from the URL $_POST sends form data as a transmission separate from the URL

15 15 $_GET Example Note the values in the URL Name:&nbsp Hometown:&nbsp <?php echo "Hello, ", $_GET["name"], " from ", $_GET["town"], "!"; ?>

16 16 $_POST Example No values in the URL Name:&nbsp Hometown:&nbsp <?php echo "Hello, ", $_POST["name"], " from ", $_POST["town"], "!"; ?>

17 17 if Statements Used to execute specific programming code if a condition returns true Used to execute specific programming code if a condition returns true Syntax: Syntax: if (conditional expression) if (conditional expression) statement ; Example: Example: $num = 5; if ($num == 5) // CONDITION IS TRUE { echo “The condition evaluates to true. ”; echo '$num is equal to ', “$num. ” } echo “This statement always executes. ”;

18 18 if...else Statements An else clause executes when the condition in an if...else statement evaluates to false An else clause executes when the condition in an if...else statement evaluates to false Syntax: Syntax: if (conditional expression) statement; else Example: Example: $Today = “Tuesday”; if ($Today == “Monday”) echo “Today is Monday ”; else echo “Today is not Monday ”; Curly braces are not required when there is only one statement after the if or else.

19 19 Nested if Statements One decision-making statement may be contained within another One decision-making statement may be contained within another if ($_GET[“SalesTotal”] > 50) { if ($_GET[“SalesTotal”] < 100) { echo “Sales total is between 50 and 100. ”; }}

20 20 switch Statements Controls program flow by executing a specific set of statements depending on the value of an expression Controls program flow by executing a specific set of statements depending on the value of an expression Compares the value of an expression to a value in a case label Compares the value of an expression to a value in a case label case label can be followed by one or more statementscase label can be followed by one or more statements Each set of statements is usually followed by the keyword breakEach set of statements is usually followed by the keyword break The default label contains statements that execute when the value of the expression does not match any other case labelThe default label contains statements that execute when the value of the expression does not match any other case label

21 21 switch Statements Syntax Syntax Switch (expression) { case label: statement(s); break; case label: statement(s); break;...default: } Example Example Switch ($day) { case 1: print “partridge”; break; case 2: print “turtle doves”; break;... default: print “Invalid”; }

22 22 Decision Practice Write a statement that prints “even” if a variable num is even. Write a statement that prints “even” if a variable num is even. Write a statement that prints “even” if a variable num is even, and “odd” otherwise. Write a statement that prints “even” if a variable num is even, and “odd” otherwise. Write a statement that prints “A” for a grade of 90-100, “B” for 80-89, “C” for 70-79, “D” for 60-69 and “F” otherwise. Write a statement that prints “A” for a grade of 90-100, “B” for 80-89, “C” for 70-79, “D” for 60-69 and “F” otherwise. Write a switch statement that takes a number and prints the corresponding month, e.g. “January” for 1. Write a switch statement that takes a number and prints the corresponding month, e.g. “January” for 1.

23 23 Repeating Code A loop statement is a control structure that repeatedly executes a statement or a series of statements A loop statement is a control structure that repeatedly executes a statement or a series of statements Each repetition of a loop is called an iteration Each repetition of a loop is called an iteration Loop may execute while a condition is true or until a condition becomes true Loop may execute while a condition is true or until a condition becomes true Four types of loops: Four types of loops: while statements do...while statements for statements foreach statements

24 24 while Statements Repeats one or more statements while a conditional expression evaluates to true Repeats one or more statements while a conditional expression evaluates to true Syntax: Syntax: while (conditional expression) while (conditional expression){statement(s); }

25 25 while Statement Example $Count = 1; while ($Count <= 5) { echo “$Count ”; ++$Count;} echo “You have printed 5 numbers. ”;

26 26 while Statement Example $Count = 10; while ($Count > 0) { echo “$Count ”; --$Count;} echo “We have liftoff. ”;

27 27 while Statements Example $Count = 1; while ($Count <= 100) { echo “$Count ”; $Count *= 2; }

28 28 Infinite Loops In an infinite loop, a loop statement never ends because its conditional expression is never false In an infinite loop, a loop statement never ends because its conditional expression is never false $Count = 1; while ($Count <= 10) { echo “The number is $Count”; }

29 29 do...while Statements Executes a statement or statements at least once Executes a statement or statements at least once Repeats execution as long as conditional expression is true Repeats execution as long as conditional expression is true Syntax: Syntax:do{ statement(s); } while (conditional expression);

30 30 do...while Example $Count = 2; do{ echo “The count is equal to $Count ”; ++$Count; } while ($Count < 2);

31 31 do...while Example $DaysOfWeek = array(“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”); $Count = 0; do{ echo $DaysOfWeek[$Count], “ ”; ++$Count; } while ($Count < 7);

32 32 for Statements Used to repeat one or more statements as long as a given condition is true Used to repeat one or more statements as long as a given condition is true Includes code that initializes a counter and changes its value with each iteration Includes code that initializes a counter and changes its value with each iteration Syntax: Syntax: for (counter declaration and initialization; condition; update statement) { statement(s); }

33 33 for Statements Example $FastFoods = array(“pizza”, “burgers”, “french fries”, “tacos”, “fried chicken”); for ($Count = 0; $Count < 5; ++$Count) { echo $FastFoods[$Count], “ ”; }

34 34 foreach Statements Used to iterate or loop through the elements in an array Used to iterate or loop through the elements in an array Does not require a counter Does not require a counter Specify an array expression within a set of parentheses following foreach Specify an array expression within a set of parentheses following foreach Syntax: Syntax: foreach ($array_name as $variable_name) {statements;}

35 35 foreach Example $animals = array( “ lion ”, “ tiger ”, “ monkey ” ); foreach ($animals as $animal) { echo “ $animal ” ; }

36 36 Loop Practice Using a do loop, do…while loop, and for loop, perform each of the following tasks: Using a do loop, do…while loop, and for loop, perform each of the following tasks: Print the numbers from 10 to 1 and then “Blastoff!”Print the numbers from 10 to 1 and then “Blastoff!” Add up the numbers from 1 to 10 and then display the result.Add up the numbers from 1 to 10 and then display the result.

37 37 Summary Functions are groups of statements that you can execute as a single unit Functions are groups of statements that you can execute as a single unit Autoglobals contain client, server, and environment information Autoglobals contain client, server, and environment information Flow control determines the order in which program statements execute Flow control determines the order in which program statements execute Decision logic includes if, if…else, and switch Decision logic includes if, if…else, and switch Loops include while, do…while, for, and foreach Loops include while, do…while, for, and foreach


Download ppt "CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals."

Similar presentations


Ads by Google