You are on page 1of 24

Course Handout Student Notebook

Contents
Unit-3 Functions in PHP 2
Learning Objective 2
Functions 3
User Defined Function 3
Function Definition 3
Function call 4
Function with arguments 4
Function with Return Value 5
Call by value and Referenc es 7
Understanding variable scope 11
Global Keyword 13
Static Variables 13
Include() and require() 16
Built-in Functions in PHP 21
Summary 23
Problems to Solve 24

Copyright IBM Corp. 2011 Course Contents 1


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
PHP Core Student Notebook

Unit-3 Functions in PHP


Learning Objective

At the end of this unit you will be able to:

Know the advantages of reusing code


Know how to write a user defined function
Understand various parts in a function.
Make use of built-in functions in PHP.

Understand the scope of variables.

Copyright IBM Corp. 2011 Unit 3 PHP Basics 2


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Functions

A function is a self-contained block of statements that performs a specific task .Functions are most useful
when you need to use the same code in more than one place. Reusing existing code reduces costs, increases
reliability, and improves consistency. Ideally, combining existing reusable components, with a minimum of
development from scratch creates a new project. If you find that your code files are getting longer, harder to
understand, and more difficult to manage, however, it may be an indication that you should st art wrapping some
of your code up into functions.

Some of the properties of a function:


It:
has a unique name.
is independent and it can perform its task without intervention from or interfering with other parts
of the program .
can take some inputs(i.e arguments) for performing a task.
returns a value to the calling program. This is optional and depends upon the task your function
is going to accomplish.

User Defined Function

Function Definition
To create a new function, use the function keyword. The syntax for declaring a function:

function function-name([argument1,argument2,...])
{
statements;
[return statement];
}
Note: Return statement and arguments are optional
Function name follow the same rules as variable name. A function may have one or many arguments. The code
(i.e statements) that will be executed each time the function is invoked should be enclosed within the braces.

Example:

<?php
function contact_info()
{
echo "IBM<br>";

3 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

echo "No:2 Indira Nagar<br>";


echo "Mumbai-41.";
}
?>

In the above example contact_info is the name of the function. This function does not return any value, and it
does not take any arguments. Wherever the contact information is needed you can invoke this function.

Function call
We can call a function by mentioning its name followed by a pair of parentheses. If the function takes
any arguments, you place the arguments between the parentheses, separated by commas. We can invoke the
contact_info function as:
contact_info( );

What happens when a function is called?

PHP looks up the function by its name (an error appears if the function has not yet been defined).
PHP substitutes the values of the calling arguments (or the actual parameters) into the variables in the
definitions parameter list (or the formal parameters).
The statements in the body of the function are executed. If any of the executed statements are return
statements, the function stops and returns the given value. Otherwise, the function completes after the
last statement is executed, without returning a value

Functions can be defined before or after they are called or invoked. The PHP interpreter reads the entire
program file and takes care of all the function definitions before it runs any of the commands in the file.

Function with arguments


As mentioned earlier a function can take some inputs (i.e arguments) for performing a task. For example
if you want to calculate an incentive amount for every employee in a company, a function can be written like the
one that follows;

Example:3.2

<?php
function calculateIncentive($salary,$incentivepercentage)
{

Copyright IBM Corp. 2011 Unit 3 PHP Basics 4


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

$incentive_amt=$salary*($incentivepercentage/100);
echo "Incentive Amount: ".$incentive_amt;
}

//To invoke or call the function

$salaryamt=25000;
$incentive_percentage=5;
calculateIncentive($salaryamt,$incentive_percentage);
>

In this example we pass salary and incentivepercentage as an input to the function, based on the input the
incentive amount is calculated. In future if the company wants to increase the incentivepercentage,it is enough to
use the incentivepercentage in the function call. Now this can be re-used for calculating the incentive for any
number of employees.

While invoking the function calculateIncentive we passed two arguments. These arguments are called actual
parameters and the arguments that appear in the function declaration are called formal parameters. In the above
examples, the arguments we passed to our functions happened to be variables. The actual parameters (that is,
the arguments in the function call) may be any expression that evaluates to a value or you can give the value
alone. The above function can also be invoked as;

calculateIncentive(25000,5);

Function with Return Value

The Return statement is used to return a value or control to the calling portion of the program. It is an
optional statement. In PHP we can return values, arrays, or object s. In example 3.2 we have printed the
incentive amount in the function itself. If we have to return the incentive amount to the calling program we can
use the return statement. Example 3.2 can be re-defined as

Example:3.3

<?php
function calculateIncentive($salary,$incentivepercentage)
{
$incentive_amt=$salary*($incentivepercentage/100);
return $incentive_amt;
}

5 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

//To invoke or call the function

$salaryamt=25000;
$incentive_percentage=5;
$incentive_amount=calculateIncentive($salaryamt,$incentive_percentage);
echo "Incentive Amount: ".$incentive_amount;
>
In the above example if you want you can write a separate function for calculating the salary as

<?php
function calculatesalary($amount)
{
if($amount<=10000)
{
$pfpercentage=6.2;
$pfamount=$amount*($pfpercentage/100);
$salary=$amount-$pfamount;
return $salary;
}
elseif($amount>10000 and $amount<=30000)
{
$pfpercentage=7.2;
$pfamount=$amount*($pfpercentage/100);
$salary=$amount-$pfamount;
return $salary;
}
elseif($amount>30000 and $amount<=40000)
{
$pfpercentage=8.2;
$pfamount=$amount*($pfpercentage/100);
$salary=$amount-$pfamount;
return $salary;
}
elseif($amount>40000)
{
$pfpercentage=10;

Copyright IBM Corp. 2011 Unit 3 PHP Basics 6


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

$pfamount=$amount*($pfpercentage/100);
$salary=$amount-$pfamount;
return $salary;
}
}
$salary=calculatesalary(29000); // Function call
$incentive_percentage=5;
$incentive_amount=calculateIncentive($salary,$incentive_percentage);
//Function call
echo "Incentive Amount: ".$incentive_amount;
>
A function call can be anywhere in the program, and it can be inside another function too. For example the
calculateIncentive function can be re-defined as

<?php
function calculateIncentive($amount,$incentivepercentage)
{
$incentive_amt=calculatesalary($amount)*($incentivepercentage/100);
return $incentive_amt;
}
//To invoke or call the function
$amount=25000;
$incentive_percentage=5;
$incentive_amount=calculateIncentive($amount,$incentive_percentage);
echo "Incentive Amount: ".$incentive_amount;
>

In the above example for calculating the incentive we need a salary amount, and so from the calculateIncentive
function we have invoked the calculatesalary function.

Call by value and References

There are two different ways of passing the arguments. The first is the most common, which is called
passing by value (or call by value), and the second is called passing by reference (or call by references).
The examples we have come across so far have used call by value. While invoking the function we pass the
value and the value is assigned to the corresponding variable in the function. In call by references instead of
the variables value being passed, the corresponding variable in the function directly refers to the passed
variable.

7 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Lets take a look at an example for call by value and references. We are going to write a function for swapping
two numbers.
Method 1: Call by value
<?php
function swap($no1,$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
$a=10;
$b=20;
echo "<h3>Before Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>";
swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>"; ?>
The output of the above code:

The contents of $a and $ have not changed, this is because the code creates a variable $a and $b with the value

Copyright IBM Corp. 2011 Unit 3 PHP Basics 8


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

10 and 20.It then calls the function swap (), variables $no1 and $no2 are created inside the function and the
values of $a and $b are copied to $no1 and $no2 and then the swapping process happens inside the function.
Now we return to the code that called it. The swapping has happened between $no1 and $no2, which is not
reflected in $a and $b.

The better approach is to use call by reference for this problem. When a parameter is passed to a function,
instead of creating a new variable, the function receives a reference to the original variable. This reference has a
variable name, beginning with a dollar sign, and can be used in exactly the same way as another variable. The
difference is that rather than having a value of its own, it merely refers to the original. So any modification made
to the reference will affect the original.

The above swap function can be modified as

Method 2: Call by Reference


<?php
function swap(&$no1,&$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
$a=10;
$b=20;
echo "<h3>Before Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>";
swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>";
?>

9 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

The output of the above code:

In the call by reference we placed an ampersand(&) before the parameter name in the function's definition. No
change is required in the function call.

Default Parameters
When declaring a function we can specify a default value for each of the last parameters. This value will
be used if the corresponding argument is left blank when calling the function. To do that, we simply have to use
the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is
not passed when the function is called, the default value is used, but if a value is specified this default value is
ignored and the passed value is used instead. For example:

function calculateSimpleInterest($principal,$noofyears, $interestrate=4)


{
$interest=$principal*$noofyears*($interestrate/100);
echo $interest;
}

calculateSimpleInterest(1000,5);

Copyright IBM Corp. 2011 Unit 3 PHP Basics 10


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

In the above example by default we have fixed the interest rate as 2, and while invoking the function we have
passed only the principal and no of years. We can invoke the same as;

calculateSimpleInterest(1000,5,6);

In this case we have passed the interest rate as 6, so the default value 2 will be over-written as 6.

Default arguments are used only in function calls where trailing arguments are omitted they must be the last
argument(s). Therefore, the following code is illegal:

function calculateSimpleInterest($principal=1000,$noofyears, $interestrate=4)


{
$interest=$principal*$noofyears*($interestrate/100);
echo $interest;
}

But we can have more than one default argument in a function, for example:

function calculateSimpleInterest($principal,$noofyears=5, $interestrate=4)


{
$interest=$principal*$noofyears*($interestrate/100);
echo $interest;
}

The above function can be invoked as

calculateSimpleInterest(1000);

Since we have given the default values for no of years and interest rate we need to pass only the principal.

CalculateSimpleInterest(1000,6); // This is also a valid function call

In the above function call we have passed both the principal and no of years.

Understanding variable scope

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP
variables can be one of four scope types:

Local variables
Function parameters
Global variables
Static variables.

Every function has its own set of variables called local variables, which can be accessed only within that

11 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

function. Any variables used outside the functions definition are not accessible from within the function by
default. When a function starts, its function parameters are defined. When you use new variables inside a
function, they are defined within the function only and dont hang around after the function call ends. The
variables that are declared outside the function are called global variables.
For example:

function myfunction()
{
$no1=10;

}
$no1=20;
myfunction();
echo $no1;

When the function myfunction() is called, the variable $no1, which is assigned 10, is only in the scope of the
function and thus does not change $no1 outside the function. So the above code snippet prints out 20.
Now suppose if we have to access or change the global variables inside the function we can use $GLOBALS[].
$GLOBALS[]
References all variables available in global scope

It is an associative array(see Unit 4) containing references to all variables which are currently defined in
the global scope of the script. The variable names are the keys of the array.
The above code snippet can be modified as:
function myfunction()
{
$GLOBALS["no1"]=10;
}
$no1=20;
myfunction();
echo $no1;

Now we get the output as 10. In myfunction() we have changed the global variable $no1 value to 10. Here
we have used $GLOBALS[] to access the global variable.

Lets consider another example for accessing a global variable:


function add()
{
$no1=10;
$no2=20;
echo $no1+$no2."<br>";

Copyright IBM Corp. 2011 Unit 3 PHP Basics 12


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

echo $no1+$GLOBALS["no2"];
}
$no2=40;
add();

In the above code for echo $no1+$no2 it prints out 30,because for $no2 it will consider the local variable. For
echo $no1+$GLOBALS["no2"] it prints out 50,here $no2 is a global variable.

Global Keyword
A global keyword enables us to declare what global variables we want to access, causing them to be
imported into the functions scope. Using the global declaration, we can inform PHP that we want a variable
name to mean the same thing as it does in the context outside the function. The syntax of this declaration is
simply the word global, variable name with a terminating semicolon.

The myfunction function can be modified as


function myfunction()
{
global $no1;
$no1=10;
}
$no1=20;
myfunction();
echo $no1;
For the above code snippet the output would be 10. It is the same as the earlier one ,the only difference being
the use of global instead of $GLOBALS[].

Note: The keyword global can be used to manually specify that a variable defined or used within a function has
global scope.

Static Variables
On each function call local variables act as though they have been newly created. The static declaration
overrides this behavior for particular variables, causing them to retain their values in between calls to the same
function.

Example:

function display()
{
static $no=10;

13 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

echo $no;
$no++;
}
display();
display();
In the above code snippet for the first function call, 10 will be initialized to $no, the output is printed as 10 and
the value of $no is incremented to 11. For the next function call the initialization will not happen, the output is
printed as 11 and again the value of $no is incremented. When static variables are used value initialization
happens only once. Lets consider another example for static variables:

<?php
function printnumbers()
{
static $count=1;
$limit=$count+10;
while($count<$limit)
{
echo $count."<br>";
$count++;
}
}
printnumbers();

printnumbers();
?>

Copyright IBM Corp. 2011 Unit 3 PHP Basics 14


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

The output of the above code:

Note: The use of static variables can be fully achieved only when they are declared inside a function.

Superglobals
Several predefined variables in PHP are "superglobals", which means they are available in all scopes
throughout a script. There is no need to invoke global $variable; to access them within functions or methods.
Some of the superglobals variables are:
$GLOBALS
$_GET
$_POST
$_FILES
$_COOKIE

15 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

$_SESSION
$_REQUEST

Include() and require()

Using include() or require()a file can be loaded into a PHP script. The file can contain anything wewould
type in a script including PHP statements, text, HTML tags, PHP functions, PHP classes. These two statements
allow to reuse any type of code and are similar like #include in C or C++.
The include() function takes all the content in a specified file and includes it in the current file. The require()
function is identical to include(), except that it handles errors differently.
Lets see an example of how to use include() and require():
The code below is saved as depositdetails.php

<?php

echo "<h4>Interest Rates for Fixed Deposit<br></h4>";


echo "Your interest is calculated on a quarterly basis for deposits of 6
months and above<br>";

?>

The code below is saved as loandetails.php

<?php

echo "<h4>Personal Loan Features & Benefits<br></h4>";


echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your
requirements.<br>";
echo "Repayment options, ranging from 10 to 60 months.<br>";
echo "If you are an bank salary account holder, we have a special offer for
you";

?>

Now another PHP program called bank.php is written, which uses depositdetails.php and loandetails.php

<?php

Copyright IBM Corp. 2011 Unit 3 PHP Basics 16


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

echo "<h4>WELCOME TO STATE BANK<br></h4>";


require("depositdetails.php");
include("loandetails.php");
echo "For net banking contact the <br>";
echo "corresponding bank where you have account";

?>

The output of the script bank.php:

When we run the file bank.php, the require and include statements (i.e) require("depositdetails.php") and
include("loandetails.php"); is replaced by the contents of the requested file, and the script is then executed.
When we load bank.php, it runs as though the script were written as:

<?php

17 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

echo "<h4>WELCOME TO STATE BANK<br></h4>";


echo "<h4>Interest Rates for Fixed Deposit<br></h4>";
echo "Your interest is calculated on a quarterly basis for deposits of 6
months and above<br>";
echo "<h4>Personal Loan Features & Benefits<br></h4>";
echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your
requirements.<br>";
echo "Repayment options, ranging from 10 to 60 months.<br>";
echo "If you are an bank salary account holder, we have a special offer for
you";
echo "<br><br>For net banking contact the corresponding bank where you have
account";
?>
Both include() and require() have the effect of placing the contents of their file into the PHP code at the point
they are called. It is not necessary that the filename extension of the included file should have .php. We can use
any extension we prefer for the files included.

In the files depositdetails.php and loandetails.php we have placed the PHP code inside the PHP tags. We
have to do this if we want PHP code within a required file treated as PHP code. If we did not open a PHP tag, the
code will just be treated as text or HTML and it will get printed as given.
For example, lets modify the loandetails.php as:

echo <h2>Loandetails<br></h2>;
<?php
echo "<h4>Personal Loan Features & Benefits<br></h4>";
echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your
requirements.<br>";
echo "Repayment options, ranging from 10 to 60 months.<br>";
echo "If you are an bank salary account holder, we have a special offer for
you";
?>
In this code we have written the echo LoanDetails outside the php tag. The output will be printed as given.

Now when we execute the bank.php the output will be:

Copyright IBM Corp. 2011 Unit 3 PHP Basics 18


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

If your company has a consistent look and feel to pages on the website, you can use PHP to add th e template
and standard elements to pages using require() and include(). You can use this template in all pages, when you
are making a minor change or completely redesigning the look of the site, you need to make the change only in
the template file. You do not have to separately alter every page in the site.

If we have a set of function definitions in a script and want to use the functions in another script then we can use
include and require. Hence, once we write a function definition in one file we can use that in N number of scripts.
Hence any modifications can be done in one file itself.

Difference Between Include and Require

include and require both work in the same manner, the only difference between them is how they fail if
the file cannot be found. The include construct will cause a warning to be printed, but processing of the script
will continue. Require, on the other hand, will cause a fatal error if the file cannot be found.
For example;

19 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

<?php

echo "<h4>WELCOME TO STATE BANK<br></h4>";


require("depositdetails1.php");
echo "For net banking contact the <br>";
echo "corresponding bank where you have account";

?>

In the above code in require we have given a file name which does not exist. When we run the bank.php script
we get the output as follows:

Since the file does not exist, we get a fatal error and the execution stops there. Now instead of require if we had
used include we will get the output as:

Copyright IBM Corp. 2011 Unit 3 PHP Basics 20


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

In the above output we get only a warning, and so the rest of the statements in the script get executed.

Include_once and Required_once

The include_once and required_once are similar to include and require, the difference is PHP will check if the
file has already been included, if so, it will not include it again. It may be used in cases where the same file might
be included and evaluated more than once during a particular execution of a script. So in this case it may help
avoid problems such as function redefinitions, variable value reassignments, etc.

Note: include(), require(), include_once(), require_once() are built- in functions in PHP.

Built-in Functions in PHP


Every language has a set of built-in functions (for example, string functions see unit 2).
For example:
echo(PHP);
print(It is a server side programming language);

Some of the Array functions in PHP are:

21 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

array()
To Create an array
sort()
Sorts an array
array_unique()
Removes duplicate values from an array
count()
Counts no of elements in an array
array_reverse()
Returns an array in the reverse order

The above functions can be made use in scripts as follows;

<?php

$company=array("IBM","TCS","CTS","WIPRO","ACCENTURE");

for($i=0;$i<count($company);$i++)
{
$sortedlist=array_reverse($company);
echo $sortedlist[$i]."<br>";
}

?>

Some of the character functions in PHP are:


ctype_upper()
Checks if all of the characters in the provided string are uppercase characters.
ctype_digit()
Checks if all of the characters in the provided string, text, are numerical.
ctype_alpha()
Checks if all of the characters in the provided string, text, are alphabetic

There are also various other function categories that are not covered here.

Copyright IBM Corp. 2011 Unit 3 PHP Basics 22


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Summary

Now that you have completed this unit, you should be able to:
Define functions to carry out specific tasks.
Invoke the function
Understand the scope of variables
Know how default arguments work
Describe some built-in functions in PHP

Identify various types of arguments

23 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Problems to Solve
1) Write a function to generate the employee id. The function should generate the employee id in a
sequential manner.
2) Write a function to calculate the tax for an employee. To calculate the tax the user should provide the
salary amount and the function should return the tax amount.
Income % of tax
>180000 10
>400000 20
<180000 Nil

3) Write a function to reverse a string. Modification should be made in the original string and temporary
string variables should not be used.
4) Write a function to swap two string values using:
a. call by value
b. call by reference
5) Write a function to calculate the average for a student. The user should provide marks for 5 subjects and
the function should return the average. Based on the average the grade is assigned. Also write another
function to find the grade. The user should receive only the grade as output.

Copyright IBM Corp. 2011 Unit 3 PHP Basics 24


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.

You might also like