0% found this document useful (0 votes)
111 views11 pages

Functions With PHP

This document provides an overview of functions in PHP. It defines functions as reusable blocks of code that accept parameters and return values. The document discusses built-in functions, how to define user-defined functions using the function keyword, variable scope within functions, passing parameters and returning values, and other function-related topics like default parameters, passing by reference, variable number of arguments, and dynamic functions. It also provides examples to demonstrate various function concepts and includes exercises for readers to practice defining functions.

Uploaded by

Jothi Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
111 views11 pages

Functions With PHP

This document provides an overview of functions in PHP. It defines functions as reusable blocks of code that accept parameters and return values. The document discusses built-in functions, how to define user-defined functions using the function keyword, variable scope within functions, passing parameters and returning values, and other function-related topics like default parameters, passing by reference, variable number of arguments, and dynamic functions. It also provides examples to demonstrate various function concepts and includes exercises for readers to practice defining functions.

Uploaded by

Jothi Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 11

PHP Functions

By
Sandun Samaratunga

Functions in PHP
Introduction
Functions are the most important part of any programming language,
PHP included. You can say in a few words that functions are pieces of
code that accept values and produce results.
function is a block of code that is not immediately executed, but can be
called by your scripts when needed. Functions can either be built-in or
defined by the user. PHP has a lot of built-in functions; one of them is
print().
Functions help you create organized and reusable code. They allow you
to abstract out details so your code becomes more flexible and more
readable. Without functions, it is impossible to write easily
maintainable programs because you're constantly updating identical
blocks of code in multiple places and in multiple files.

PHP Code:
<?php
function myFunction() //no semicolon here!
{
print <h1>This is my first function</h1>;
}
myFunction();
?>

Note: Your function name can start with a letter or underscore "_", but
not a number!
To declare a function, use the function keyword, followed by the name
of the function and any parameters in parentheses. To invoke a
function, simply use the function name, specifying argument values for
any parameters to the function. If the function returns a value, you can
assign the result of the function to a variable.

Variable Scope
Up to now you can used declared any variable anywhere in a page.
With functions this is no longer always true. Functions keep their sets
of variables that are distinct from those of the page and of page and of
other functions.
The Variables defined in a function, including its parameters, are not
accessible outside of the function, and by default, variables defined
outside a function are not accessible inside the function.
<?php
$text='Hey Im in a pag';
?>
<P>this is a web page<P>
<?php
echo $text;
?>
<BR>
<?php
$a=3;
function Add()
{
$a+=2;
echo $a.'<BR>';
}
Add();
echo $a;
?>

Global Variable
If you want a variable in the global scope be accessible with in a
function, you can use the global keyword.
<?php
$a=3;
function Add()
{
global $a;
$a+=2;
echo $a;
}
Add();
echo $a;
?>
3

You must include the global keyword in a function before any uses of the
global variable or variables you want to access. Because they are
declared before the body of the function, Function parameters can never
be globale.
Static Variables
Static variable is shared between all calls to the functions and it is
initialized only the first time the function is, called.
Use static keyword to declare a static variable.
<?php
Function counter(){
static $count=0;
return $count++;
}
for($i=0;$i<=5;$i++)
{
echo counter ();
}
?>

Passing Parameters and getting the returned value


// add two numbers together
function add($a, $b) {
return $a + $b;
}
$total = add(2, 2);
Exercise 1
Define a function to get a positive integer as input parameter and to
return the sum of all integers from 1 up to that number.
Inside the function, it doesn't matter whether the values are passed in
as strings, numbers, arrays, or another kind of variable. You can treat
them all the same and refer to them using the names from the
prototype.
You don't need to (and, in fact, can't) describe the type of variable
being passed
4

in. PHP keeps track of this for you.


Also, unless specified, all values being passed into and out of a
function are passed by value, not by reference. This means PHP makes
a copy of the value and provides you with that copy to access and
manipulate. Therefore, any changes you make to your copy don't alter
the original value.

Exercise 2
Define a function that takes number as input, incremented by one and
printed on the screen.
Outside the function, declare variable and initialize it to 10. Call to the
function and print the variable (outside the function)

Setting Default Values for Function Parameters


<?php
function Mult($num1, $num2 = 1) {
echo "$num*$num2";
}
Mult(5);
Mult(5,12);
?>

Exercise 3
Define a function that takes 2 parameters (String and character
representing text effect) and prints in that string with the text effect.
Default text effect should be Bold. If user wants, he can pass
character for Italics and Underline too.

Passing Values by Reference


You can pass variable to function by reference, so that function could modify its
arguments. The syntax is as follows:
<?php
function PassByReference(&$var)
{
$var++;
}
$a=5;
echo 'Before Call Function $a :'.$a;
PassByReference ($a);
echo 'After Call Function $a :'.$a;
// $a is 6 here
?>

&: Reference Sign


Note that there's no reference sign on function call - only on function definition. Function
definition alone is enough to correctly pass the argument by reference
Creating Functions That Take a Variable Number of Arguments
Method 1: Using Arrays
function total($numbers) {
// initialize to avoid warnings
$sum = 0;
// the number of elements in the array
$size = count($numbers);
// iterate through the array and add up the numbers
for ($i = 0; $i < $size; $i++) {
$sum += $numbers[$i];
}
return $sum;
}
$tot = total(array(96, 93, 97));

Method 2: in-built function


function total() {
// initialize to avoid warnings
$sum = 0;
// the number of arguments passed to the function
$size = func_num_args();
// iterate through the arguments and add up the numbers
for ($i = 0; $i < $size; $i++) {
$sum += func_get_arg($i);
}
return $sum;
}
$tot = total(96, 93, 97);
This example uses a set of functions that return data based on the
arguments passed to the function they are called from. First,
func_num_args( ) returns an integer with the number of arguments
passed into its invoking function.
From there, you can then call func_get_arg( ) to find the specific
argument value for each position.
Exercise 5
Extend above to methods to get return the average of set of numbers.

Returning More Than One Value


Return an array and use list( ) to separate elements.
function time_parts($time) {
return explode(':', $time);
}
list($hour, $minute, $second) = time_parts('12:34:56');
You pass in a time string as you might see on a digital clock and call
explode( ) to break it apart as array elements. When time_parts( )
returns, use list( ) to take each element and store it in a scalar
variable.

If you want, You can also use global variables.


function time_parts($time) {
global $hour, $minute, $second;
list($hour, $minute, $second) = explode(':', $time);
}
time_parts('12:34:56');

Skipping Selected Return Values


A function returns multiple values, but you only care about some of
them.
Omit variables inside of list( )
function time_parts($time) {
return explode(':', $time);
}
list(, $minute,) = time_parts('12:34:56');

Exercise 6
Extend the above example so that time part HOURS get returned and
to display some greeting message based on the time. Eg: if hrs<12,
Good Morning.

Calling Variable Functions


function eat_fruit($fruit) { print "chewing $fruit."; }
$function = 'eat_fruit';
$fruit = 'kiwi';
$function($fruit); // calls eat_fruit( )
Exercise 7
Define three different functions that take two numbers as input
parameters and print addition, subtraction and multiplication
respectively.
Outside to functions, do following steps.
1. Declare two variables and assign them with 10 &15.
2. Generate random number.
HINT: To generate a random number between two end points,
pass mt_rand( ) two arguments:
$random_number = mt_rand(1, 100);
3. If random number is <20, you should get printed the addition of
above two numbers (10 &15)
If 20<=random number <50, you should get printed the
substraction of above two numbers (10 &15)
If random number is >50, you should get printed the
multiplication of above two numbers (10 &15)
RULE: YOU CAN USE ONLY ONE FUNCTION CALL INSIDE YOUR
PROGRAM.
Creating Dynamic Functions
Use create_function( )
$add = create_function('$i,$j,$k', 'return $i+$j+$k;');
$add(1, 1,3); // returns 2
The first parameter to create_function( ) is a string that contains the
arguments for the function, and the second is the function body.

10

Predefined functions
Date manipulation function
Get Current date (date() function)
<?php
$today = date("F j, Y");
echo "$today";
$today = date("d / M/ Y");
echo "$today";
?>
Write a program to get the date in 12th December 2008 like?
<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a");
pm
$today = date("m.d.y");
$today = date("j, n, Y");
$today = date("Ymd");
$today = date('h-i-s, j-m-y, it is w Day z ');
1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');
$today = date("D M j G:i:s T Y");
MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');
$today = date("H:i:s");
?>

// March 10, 2001, 5:16


//
//
//
//

03.10.01
10, 3, 2001
20010310
05-16-17, 10-03-01,

// It is the 10th day.


// Sat Mar 10 15:16:08
// 17:03:17 m is month
// 17:16:17

Find dates in the future or the past


<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),
date("Y"));
$nextyear = mktime(0, 0, 0, date("m"),
date("d"),
date("Y")+1);
echo date('d/M/y',$tomorrow)."<br>";
echo date('d/M/y',$lastmonth)."<br>";
echo date('d/M/y',$nextyear)."<br>";
?>

Note: This can be more reliable than simply adding or subtracting the number of seconds
in a day or month to a timestamp because of daylight saving time.

11

You might also like