0% found this document useful (0 votes)
41 views

WS 101 - SG2

This document provides a study guide for a module on functions and arrays in PHP. It discusses creating and invoking functions, using parameters in functions, and the scope of variables. It also covers creating arrays, accessing array elements, and iterating through elements using loops. The module aims to teach students how to create reusable code through functions, pass input values to functions, and efficiently store and manipulate groups of related data using arrays.

Uploaded by

karina abyys
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

WS 101 - SG2

This document provides a study guide for a module on functions and arrays in PHP. It discusses creating and invoking functions, using parameters in functions, and the scope of variables. It also covers creating arrays, accessing array elements, and iterating through elements using loops. The module aims to teach students how to create reusable code through functions, pass input values to functions, and efficiently store and manipulate groups of related data using arrays.

Uploaded by

karina abyys
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

FM-AA-CIA-15 Rev.

0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

STUDY GUIDE FOR MODULE NO. 2

FUNCTIONS AND ARRAYS


MODULE OVERVIEW

In this module, you will learn about PHP functions on how to create and invoke functions as well
as the use of parameters in a function and the scope of variables in a function. You will also
explore arrays. Arrays are a very powerful feature of any programming language because they
let you easily work with large amounts of similar data. You will learn how to create, access,
iterate array elements and manipulate some array functions as well as the different types of
arrays.

MODULE LEARNING OBJECTIVES

At the end of the module, students are expected to:

1. Learn how to create and invoke functions


2. Describe the use of parameters in a function
3. Understand the use of global and local scope of variables in a function
4. Learn how to create an array
5. Discover how to access array elements and how to use loops to iterate elements of an
array
6. Identify the indexed, associative and multi-dimensional arrays
7. Learn how to manipulate an array using array functions

LEARNING CONTENTS (Creating and Invoking Functions)

2.1. Creating and Invoking Functions

A function is a set of program statements that perform a specific task, and that can be
called, or executed, from anywhere in your program.

You can create a function by using keyword function() and inserting the code in the
function block.

Syntax

function myFunc(){
// Code to be executed
}

The declaration of a user-defined function start with the word function, followed by the name
of the function you want to create followed by parentheses i.e. () and finally place your
function's code between curly brackets {}.

There are three reasons why you should used functions:

1. User-defined functions enable developers to extract commonly used pieces of


code into separate packages, thereby reducing unnecessary code repetition and
redundancies. This separation of code into independent subsection also makes the
easier to understand and debug.

PANGASINAN STATE UNIVERSITY 1


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

2. Because functions are defined once (but used many times), they are easy to
maintain. A change to the function code need only be implemented in a single
place – the function definition – with no changes needed anywhere else.
Contrast this with non abstracted approach, where implementing a change
means tracking down and manually changing every occurrence of the earlier
version of the code.
3. Because functions force developers to think in abstract terms (define input and
output values, set global and local scope, and return specific tasks into generic
components), they encourage better software design and help in creating
extensible applications.

To invoke the function you should call it by name of the function. However, if you want
to return a value from the function you should need to insert the keyword return
followed by an expression inside your function. Once the PHP interpreterencounters
the return keyword from the function this will stops execution of the function and
returns expression as the function’s value. This is the reason way the return keyword
always inserted at the last statement of your function.

LEARNING CONTENTS (Function with Parameters)

2.2 Function with Parameters

You can specify parameters when you define your function to accept input values at
run time. The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the function at
the time of invocation.

Syntax

function myFunc($arg1, $arg2){


// Code to be executed
}

function square ($x) {


return $x*$x;
}
echo “The square of 5 is “. square(5);

LEARNING CONTENTS (Scope of a Variable)

2.3 Scope of a Variable

You can declare the variables anywhere in a PHP script. But, the location of the
declaration determines the extent of a variable's visibility within the PHP program i.e.
where the variable can be used or accessed. This accessibility is known as variable
scope.

PANGASINAN STATE UNIVERSITY 2


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

By default, variables declared within a function are local and they cannot be viewed or
manipulated from outside of that function, as demonstrated in the example below:

Example

<?php
// Defining function functiontest(){
$greet= "Hello World!";
echo $greet; } test(); // Outputs: Hello World!
echo $greet; // Generate undefined variable error ?>

You can make the variable available by using the keyword global that makes a variable
available at any location in the program. For instance, the following function creates a
variable:

<?php
$greet= "Hello World!";
// Defining function functiontest(){
global $greet;
echo $greet; }
test(); // Outpus: Hello World!
echo $greet; // Outpus: Hello World!
// Assign a new value to variable $greet= "Goodbye";
test(); // Outputs: Goodbye
echo $greet; // Outputs: Goodbye ?>

PANGASINAN STATE UNIVERSITY 3


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

LEARNING ACTIVITY 1

Checkpoint: Home-based Activity

The following will be submitted on the specified date. It includes soft copy of the UI and codes
and the physic al files for the activity.

1. Create a simple web application that converts decimal into binary, octal, hexadecimal using
functions and arrays. Reminder: Do not use built in functions for the conversion.

LEARNING CONTENTS (Arrays)

2.4 Arrays

Arrays are complex variables that allow us to store more than one value or a group of
values under a single variable name. Let's suppose you want to store colors in your PHP
script. Storing the colors one by one in a variable could look something like this:

<?php
$color1= "Red";
$color2= "Green";
$color3= "Blue";
?>
But what, if you want to store the states or city names of a country in variables and this
time this not just three may be hundred. It is quite hard, boring, and bad idea to store
each city name in a separate variable. And here array comes into play.

2.4.1 Declaring an Array

There are several ways to declare an array in PHP however the simplest way to declare
an array is to assign a value to a variable with square brackets ([ ]) at the end of its
name.

Here’s an example.

$color[1] = “Red”;
$color[2] = “Green”;
$color[3] = “Blue”;

The array $color[] holds three values: Red, Green, and Blue. Also, you can use
characters as the index of the array such as:

$color[A] = “Red”;
$color[B] = “Green”;
$color[C] = “Blue”;

Another, you can also leave the square bracket blank for example.

$color[] = “Red”;
$color[] = “Green”;

PANGASINAN STATE UNIVERSITY 4


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

$color[] = “Blue”;

Remember that the index number of an array always start with 0 to N-1. Therefore if we
want to display value “aso” from the array $color, we will place 1 inside the square
bracket such as$color[1].

Finally, you can use array construct to declare an array. The array construct can be
declared using the array() keyword, which generally takes the following form (elements
inside square brackets, [], are optional

$color = array(‘Red’, ‘Green’, ‘Blue’);//the first value index number is 0

LEARNING CONTENTS (Accessing Array Elements)

2.5 Accessing Array Elements

Reading the values of an array is similar to variable. However in PHP, you can use several
array functions to manipulate arrays values.

Example1
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$myAuthor = $authors[0];
$anotherAuthor = $authors[1];

Example2
$myBook = array("title" = > "The Grapes of Wrath", "author" = > "John Steinbeck",
"pubYear" = > 1939 );
$myTitle = $myBook["title"];
$myAuthor = $myBook["author"];

LEARNING CONTENTS (Iterating Elements in an Array)

2.6 Iterating Elements in an Array

In dealing with arrays using C/C++ we usually used for loop to access the array values.
Using forloop:

<?php
$authors = array("Steinbeck", "Kafka", "Tolkien", "Dickens" );
for ($i = 0; $i<sizeof($authors);$i++)
echo $author[$i]."<br>\n";
?>

The function sizeof() is mostly used in loop counters that the loop iterates as many times as
there are elements in the array.

There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value) statement;


foreach (array_expression as $key => $value)statement;

<?php
$authors = array("Steinbeck", "Kafka", "Tolkien", "Dickens" );
foreach ( $authors as $val ) {
echo "$val .<br/ > ";
}
?>
PANGASINAN STATE UNIVERSITY 5
FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

$myBook = array("title" => "The Grapes of Wrath", "author" =>


"John Steinbeck","pubYear" => 1939 );
foreach ( $myBook as $key = > $value ) {
echo $key. " ".,$value;
}

LEARNING CONTENTS (Types of Arrays in PHP)

2.7 Types of Arrays in PHP

There are three types of arrays that you can create. These are:

 Indexed array — An array with a numeric key.


 Associative array — An array where each key has its own specific value.
 Multidimensional array — An array containing one or more arrays within itself.

2.7.1 Indexed Arrays

 <?php // Define an indexed array


 $authors = array("Steinbeck", "Kafka", "Tolkien", "Dickens" );
 ?>


 <?php
 $authors[0] = "Steinbeck";
 $authors[1] = "Kafka";
$authors[2] = "Tolkien";
?>

2.7.2 Associative Arrays

In an associative array, the keys assigned to values can be arbitrary and user defined
strings. In the following example the array uses keys instead of index numbers:

<?php
// Define an associative
$myBook = array("title" = > "The Grapes of Wrath", "author" = >
"John Steinbeck", "pubYear" = > 1939 );

2.7.3 Defining a MultidimensionalArray

In some cases, we need to store multiple data which two-dimensional array is one of the
useful to utilize. Multi-dimensional arrays is an array of arrays also called nested array

Defining a multidimensional array is fairly straightforward, as long as you remember that


what you are working with is actually an array that contains more arrays.

You can initialize values by using references to the individual elements, as follows:

PANGASINAN STATE UNIVERSITY 6


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

$temps[0]["title"] = "The Grapes of Wrath";

<?php

$myBook=array(array("title"=>"The Grapes of Wrath","author"=>"John

Steinbeck","year"=>1979),array("title"=>"The Trial","author"=>"Franz

Kafka","year"=>1925),array("title"=>"The Hobbit","author"=>"J. R. R.

Tolkien","year"=>1937));

?>

Accessing Multidimensional Arrays

foreach($myBook as $book){

$count++;

echo "Book # $count<br/><br/>";

foreach($book as $value){

echo "$value<br/>";

?>

LEARNING CONTENTS (Manipulating Arrays)

2.8 Manipulating Arrays

One of the powerful feature of arrays in most languages is that you can sort the elements in
any order you like, add and delete elements.
Here are some of the commonly used array functions.

 array_pop() - Pop the element off the end ofarray


 array_push() - Push one or more elements onto the end ofarray
 array_search() - Searches the array for a given value and returns the
corresponding key ifsuccessful

For array_pop() here’s an example:

<?php
$color = array(1=>’Red’, 2=>’Green’,3=>’Blue’);
$append = array_pop($color);
echo $append;
?>
PANGASINAN STATE UNIVERSITY 7
FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

After this, $color will have only 2 elements and Blue will be assigned to $append.

For array_push() here’s an example:

<?php
$color = array(’Red’, ’Green’);
array_push($color,’Blue’,’Violet’);
print_r $color;
?>

This example would result in $color having the following elements:

Array (
[0] => Red
[1] => Green
[2] => Blue
[3] => Violet
)

<?php
$color = array(A => 'Red', B=>'Green', C=>'Blue',D=>'Violet');
$key = array_search('Green', $array); // $key =B;
$key =array_search('Violet',$array); // $key = D;
?>

 sort() - sort an array

<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . “<br/>";
}
?>

PANGASINAN STATE UNIVERSITY 8


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

LEARNING ACTIVITY 2

Checkpoint: Home-based Activity

The following will be submitted on the specified date. It includes soft copy of the UI and codes
and the physic al files for the activity.

2. Modify the quiz application in the previous module, this time create a 10-point quiz using a
multidimensional array with the use of HTML elements (forms and tables).

$arr=array(
array("It is referred to as the center of the solar
system.","sun","moon","jupiter","earth"),array("Where does the sun
shines?","west","north","south","east"));

Provide an array of answer key and it must check the selected answers of the user.

1. Where does the sun shines?

O north O east O south O west

SUBMIT

Output:

You got 3/10!

PANGASINAN STATE UNIVERSITY 9


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (WS101 Web Systems and Technologies 1) Module No. 2

SUMMARY

In this module, it has introduced you to another important concepts: functions and arrays. You
delved into the anatomy of arrays, declaring, accessing and iterating array elements, learned
the concepts of indexed, associative and multidimensional arrays and how to manipulate an
array.

REFERENCES

Gosselin, D. (2011). Php with MySQL.

Pomperada, J. R. (2015). Php with MySQL : A Web programming language.

Online learning materials

tutorialrepublic.com/php-tutorial

php.net

tutorialrepublic.com/php-examples.php

PANGASINAN STATE UNIVERSITY 10

You might also like