WS 101 - SG2
WS 101 - SG2
0 10-July-2020
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.
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 {}.
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.
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
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.
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 ?>
LEARNING ACTIVITY 1
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.
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.
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”;
$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
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"];
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:
<?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
There are three types of arrays that you can create. These are:
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 );
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
You can initialize values by using references to the individual elements, as follows:
<?php
Steinbeck","year"=>1979),array("title"=>"The Trial","author"=>"Franz
Kafka","year"=>1925),array("title"=>"The Hobbit","author"=>"J. R. R.
Tolkien","year"=>1937));
?>
foreach($myBook as $book){
$count++;
foreach($book as $value){
echo "$value<br/>";
?>
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.
<?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
After this, $color will have only 2 elements and Blue will be assigned to $append.
<?php
$color = array(’Red’, ’Green’);
array_push($color,’Blue’,’Violet’);
print_r $color;
?>
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;
?>
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . “<br/>";
}
?>
LEARNING ACTIVITY 2
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.
SUBMIT
Output:
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
tutorialrepublic.com/php-tutorial
php.net
tutorialrepublic.com/php-examples.php