rabeeajaffari.files.wordpress.com  · web viewpart a: control structures: control structures help...

13
Department of Software Engineering Mehran University of Engineering and Technology, Jamshoro Course: SW412 – Web Technologies Instructo r Rabeea Jaffari Practical/Lab No. 07 Date CLOs CLO-3: P5 Signature Assessment Score Topic To become familiar with control structures and arrays in PHP Objectives - To learn conditional statements - To learn loops - To learn jump statements - To learn about arrays Lab Discussion: Theoretical concepts and Procedural steps Part A: Control Structures : Control structures help to control the flow of the program (default flow is sequential flow i.e. line by line). Various types of control structures are as follows: Selection statements: Help to choose between two or more than two-alternatives (if, if-else, if-else-if, switch) statements. Iteration statements: Help to repeat a statement or group of statements multiple times (for, while, do-while, foreach) loops. Jump statements: Help to transfer program control from one part to another part of the program. (labels with goto, break, continue) 1. Selection statements: The syntax for various selection statements is as follows: If statement: Used to choose only between two alternatives (choices). if (condition) { statement(s); }

Upload: others

Post on 04-Sep-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Department of Software EngineeringMehran University of Engineering and Technology, Jamshoro

Course: SW412 – Web TechnologiesInstructor Rabeea Jaffari Practical/Lab No. 07Date CLOs CLO-3: P5Signature Assessment Score

Topic To become familiar with control structures and arrays in PHPObjectives - To learn conditional statements

- To learn loops- To learn jump statements- To learn about arrays

Lab Discussion: Theoretical concepts and Procedural steps

Part A: Control Structures : Control structures help to control the flow of the program (default flow is sequential flow i.e. line by line). Various types of control structures are as follows:

Selection statements: Help to choose between two or more than two-alternatives

(if, if-else, if-else-if, switch) statements. Iteration statements: Help to repeat a statement or group of statements

multiple times(for, while, do-while, foreach) loops.

Jump statements: Help to transfer program control from one part to another part of the program.

(labels with goto, break, continue)

1. Selection statements: The syntax for various selection statements is as follows:

If statement: Used to choose only between two alternatives (choices).

if (condition) {statement(s);

}

If-else statement: Used to choose only between two alternatives (choices).

if (condition) {statement(s);

}else {statement(s);

}

If-else-if/ If-elseif statement: Used to choose between multiple alternatives (choices).

Page 2: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

There are two possible ways of using else if keyword in PHP i.e. either separated into two words as else if or used as a single word (without any space) elseif.

if (condition) {statements;} elseif(condition) { //single wordstatements;} else {statements;}

if (condition) {statements;} else if(condition) { //two separate wordsstatements;} else {statements;}

elseif and else if are considered exactly the same when using curly brackets as in the above example not in the colon notation though (discussed ahead).

Switch statement: Used to choose between multiple alternatives (choices).

switch (n) {case label1:

//code to be executed if n=label1;break;

case label2://code to be executed if n=label2;break;

case label3://code to be executed if n=label3;break;

default://code to be executed if n is different from all labels;

}

2. Iteration statements: The syntax for various iteration statements is as follows:

For loop: Also known as counter controlled loop because executes a fixed number of times as specified by the counter limit.

for (initialization; condition; update) {statement(s);

}

Page 3: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

The php code file above prints squares of numbers from 0-10 using for loop.

While loop: It is also known as the pre-test loop because it tests the condition first and then executes the statements in it if the condition is true or terminates otherwise.

while (condition) {statement(s);

}

Do-While loop: A do-while loop is similar to a while loop for repeating statement(s) but is known as post-test loop because it executes the statements in its body at least once and then checks the condition at last. Thus a do while loop is guaranteed to execute at least once even when its condition is false the very first time

do {statement(s);

} while (condition);

Foreach loop: The foreach loop provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.  The syntax of the loop along with an example is given below:

For ordinary arrays:

foreach (array_expression as $value){ statement(s)}

For associative arrays (discussed ahead):

foreach (array_expression as $key => $value){ statement(s)}

The php code file above prints the array elements contained in $a using the foreach loop.

In order modify array elements within the foreach loop precede $value with an ampersand sign &. In that case the value will be assigned by reference.

<?php

$a = array(1, 2, 3, 17);foreach ($a as $v) {    echo "Current value of \$a: $v.\n";}?>

Page 4: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Reference of a $value using & in the above example will remain even after the foreach loop so it is recommended to destroy it by unset() method.

Alternative syntax for PHP control structures:

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. An example is shown below:

It should be noted that this colon (:) notation only works with elseif (single word without spaces) version of the if-else-if statement and not the other one.

3. Jump statements: The syntax for various jump statements is as follows:

Break statement: The break statement can only be used in loop or switch statement in PHP.

<?php$arr = array(1, 2, 3, 4);foreach ($arr as &$value) { //the & sign    $value = $value * 2;}// $arr is now changed to array(2, 4, 6, 8)unset($value); // break the reference with the last element?>

<?phpif ($a == 5):    echo "a equals 5";    echo "...";elseif ($a == 6):    echo "a equals 6";    echo "!!!";else:    echo "a is neither 5 nor 6";endif;?>

Page 5: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Continue statement: The continue statement in PHP is commonly used in loop. In other words, a certain condition is true in the loop, by continuing to skip the program execution and continuing to go to the next program works.

Goto statement: select a label (any name used to identify part of the program) with goto statement and immediately transfer the control to the part of program identified by that label.

Page 6: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

The above php code will output:

j hit 17

Part B: Arrays: An array is a data structure that stores one or more similar type of values in a single value. Three types of arrays are supported by PHP:1. Numeric array-An array with a numeric index. Values are stored and accessed in linear fashion2. Associative array-An array with strings as index (keys). This stores element values in association with key values rather than in a strict linear index order.3. Multidimensional array-An array containing one or more arrays and values are accessed using multiple indices i.e. array of arrays.

The foreach loop is usually used to loop through the arrays. Examples of arrays are shown below. All three types of arrays are created using the built-in array() constructor in PHP.

Numeric Array:

<?phpfor($i=0,$j=50; $i<100; $i++) {  while($j--) {    if($j==17) 

goto end;  //jump to end label  }  }echo "i = $i";end:   //labelecho 'j hit 17';

Page 7: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Associative Array:

Multidimensional Array:

Useful Array Functions: Some useful array functions are given below:

Page 8: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

count():Returns the number of elements in the array.sizeof():same as count()

key(): Fetch a key from an array

array_push():Push one or more elements onto the end of array. Returns the new number of elements in the array. Array_push($array, “value”);

array_pop():Pop the element off the end of array. Returns the last value of array. If array is empty (or is not an array), NULL will be returned. array_pop($stack);

array_pad(): Used to resize an array. Returns a copy of the array padded to size specified by sizewith value value.$input = array(12, 10, 9);$result = array_pad($input, 5, 0);// result is array(12, 10, 9, 0, 0)

array_reverse(): Return an array with elements in reverse order. If preserve_keysis set as true, the numeric keys will be preserved.

array_search(): Searches the array for a given value and returns the corresponding key if successful. array_search(“green”, $array)

sort(input_array, sort_flags)This function sorts an array. Elements will be arranged from lowest to highest when this function has completed. Possible sort_flags that can be supplied to the argument are:

SORT_FLAGS: SORT_REGULAR: compare items normally SORT_NUMERIC: compare items numerically SORT_STRING: compare items as strings SORT_NATURAL: compare items as strings using "natural ordering“ SORT_FLAG_CASE: sort strings case-insensitively

asort(): accepts an associative array and sorts its values just as sort() doesarray_values(): Return all the values of an arrayarray_keys(): Return all the keys or a subset of the keys of an array. array_keys()—Return all the keys or a subset of the keys of an array.array_key_exists(): Checks if the given key or index exists in the arrayin_array():Checks if a value exists in an array. in_array(“hello”, $arr);

Lab Tasks

Page 9: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Submission Date: 07-01-19 (Part A only)

Part A: Write PHP code to implement various control structures according to the requirements given below:

1. Iterate the integers from 1 to 50. For multiples of three print "Star" instead of the number and for the multiples of five print "Struck". For numbers which are multiples of both three and five print "StarStruck"

2. Create a PHP variable $d = 'A00'. Using this variable print the following numbers. A01 A02 A03 A04 A05

3. Store any number with two digits or above in a PHP variable and calculate its sum. If the sum is equal to your roll number, output a statement that prints “It’s your lucky day today.” Use if-elseif decision statement with the colon (:) syntax.

4. Store any name in a PHP variable and then loop through it printing the name of a thing (similar to alphabet books) corresponding to each letter of the name. For example:

Name: SaadOutput: Stairs Apple Apple Duck

Hint: Use decision statement (switch or if-else-if) with a loop.

5. Use labels to identify loops that print even and odd numbers respectively. First print even numbers till 10 and then use goto statement to jump to the loop that prints odd numbers till 9.

6. Output the following multiplication table using loops (Hint: you’ll need to use nested loops to print the table below).

Page 10: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

Part B: Write PHP code to implement various arrays according to the requirements given below: (use array functions where necessary)

1. $arr = array( "Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels", "Denmark"=>"Copenhagen", "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava", "Slovenia"=>"Ljubljana", "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin", "Netherlands"=>"Amsterdam", "Portugal"=>"Lisbon", "Spain"=>"Madrid", "Sweden"=>"Stockholm", "United Kingdom"=>"London", "Cyprus"=>"Nicosia", "Lithuania"=>"Vilnius", "Czech Republic"=>"Prague", "Estonia"=>"Tallin", "Hungary"=>"Budapest", "Latvia"=>"Riga", "Malta"=>"Valetta", "Austria" => "Vienna", "Poland"=>"Warsaw") ;Display the capital and country name from the above array $arr. Sort the list by the capital of the country.

Sample Output :The capital of Netherlands is Amsterdam The capital of Greece is Athens The capital of Germany is Berlin 

2. Create a numeric array, increase the size of the array by inserting two new special characters ($,*,@ or any other) into it at any given positions, remove the first element of the array, print the final result.

3. Displays all the numbers between 200 and 250 that are divisible by 4 without using any control structure. (Hint: make use of the range() function).

4. Remove any duplicate values from two numeric arrays containing numbers and strings respectively. (Hint: make use of array_unique() function).

5. Write a PHP script to print "First", “White” and 2 from the following multi-dimensional array.

Sample Data: $color = array ( "color" => array ( "a" => "Red", "b" => "Green", "c" => "White"),"numbers" => array ( 1, 2, 3, 4, 5, 6 ),"holes" => array ( "First", 5 => "Second", "Third"));

6. Sort the following associative array:array("Samreen"=>"31","Jahan"=>"41","Warisha"=>"39","Rania"=>"40") in

a) ascending order sort by valueb) ascending order sort by Keyc) descending order sorting by Valued) descending order sorting by Key

Page 11: rabeeajaffari.files.wordpress.com  · Web viewPart A: Control Structures: Control structures help to control the flow of the program (default flow is sequential flow i.e. line by

7. Generate unique random numbers within a range of (1-200) and store them in an array. Search for your roll number in the generated array and print “Found you” if the roll number exists in it.