PHP User-defined functions

PHPServer Side ProgrammingProgramming

Introduction

PHP has a large number of built-in functions such as mathematical, string, date, array functions etc. It is also possible to define a function as per specific requirement. Such function is called user defined function.

A function is a reusable block of statements that performs a specific task. This block is defined with function keyword and is given a name that starts with an alphabet or underscore. This function may be called from anywhere within the program any number of times.

Syntax

//define a function
function myfunction($arg1, $arg2, ... $argn)
{
   statement1;
   statement2;
   ..
   ..
   return $val;
}
//call function
$ret=myfunction($arg1, $arg2, ... $argn);

Function may be defined with optional but any number of arguments. However, same number of arguments must be provided while calling. Function's body can contain any valid PHP code i.e. conditionals, loops etc. (even other functions or classes may be defined inside a function). After executing statements in the block, program control goes back to the location from which it was invoked irrespective of presence of last statement of function block as return. An expression in front of return statement returns its value to calling environment.

user defined function Example

In following example shows definition and call to a usr defined function sayhello()

Example

 Live Demo

<?php
//function definition
function sayHello(){
   echo "Hello World!";
}
//function call
sayHello();
?>

This script will produce following result when run from command line −

Output

Hello World!

function with arguments

In following example, a function is defined with two formal arguments

Example

 Live Demo

<?php
function add($arg1, $arg2){
   echo $arg1+$arg2 . "\n";
}
add(10,20);
add("Hello", "World");
?>

Output

This will produce following result. −

30
PHP Warning: A non-numeric value encountered in line 3

In second call, two string values are given as function arguments. Since PHP doesn't support + operator for strings, a warning is emitted.

function return

User defined function in following example processes the provided arguments and retuns a value to calling environment

Example

 Live Demo

<?php
function add($arg1, $arg2){
   return $arg1+$arg2;
}
$val=add(10,20);
echo "addition:". $val. "\n";
$val=add("10","20");
echo "addition: $val";
?>

Output

This will produce following result. −

addition:30
addition:30

In second call, even if arguments are string, PHP cooerces them into integer and performs addition

function with default argument value

While defining a function , a default value of argument may be assigned. If value is not assigned to such agument while calling the function, this default will be used for processing inside function. In following example, a function is defined with argument having default value

Example

 Live Demo

<?php
function welcome($user="Guest"){
   echo "Hello $user\n";
}
//overrides default
welcome("admin");
//uses default
welcome();
?>

Output

This will produce following result. −

Hello admin
Hello Guest

In second call, function is called without passing value. In this case, user argument takes its default value.

function with variable number of arguments

It is possible to define a function with ability to receive variable number of arguments. The name of formal argument in function definition is prefixed by ... token. Following example has add() function that adds a list of numbers given as argument

Example

 Live Demo

<?php
function add(...$numbers){
   $ttl=0;
   foreach ($numbers as $num){
      $ttl=$ttl+$num;
   }
   return $ttl;
}
$total=add(10,15,20);
echo "total= $total\n";
echo "total=". add(1,2,3,4,5). "\n";
?>

Output

This will produce following result. −

total= 45
total=15

It is also possible to obtain a list of arguments passed to a function with the help offunc_get_args() function. We can run a PHP loop to traverse each value in the list of arguments passed. In that case the function definition doesn't have a formal argument.

Example

 Live Demo

<?php
function add(){
   $numbers=func_get_args();
   $ttl=0;
   foreach ($numbers as $num){
      $ttl=$ttl+$num;
   }
   return $ttl;
}
$total=add(10,15,20);
echo "total= $total\n";
echo "total=". add(1,2,3,4,5). "\n";
?>

Output

This will produce following result. −

total= 45
total=15

function within another function

A function may be defined inside another function's body block. However, inner function can not be called before outer function has been invoked.

Example

 Live Demo

<?php
function hello(){
   echo "Hello\n";
   function welcome(){
      echo "Welcome to TutorialsPoint\n";
   }
}
//welcome();
hello();
welcome();
?>

Remove the comment to call wlcome() bfore hello(). Following error message halts the program −

Fatal error: Uncaught Error: Call to undefined function welcome()

Output

Comment the line and run again

Hello
Welcome to TutorialsPoint

Recursive function

A function that calls itself is called recursive function. Calling itself unconditionally creates infinite loop and results in out of memory error because of stack full. Following program calls factorial() function recursively

Example

 Live Demo

<?php
function factorial($n){
   if ($n < 2) {
      return 1;
   } else {
      return ($n * factorial($n-1));
   }
}
echo "factorial(5) = ". factorial(5);
?>

Output

factorial(5) = 120
raja
Published on 18-Sep-2020 17:27:22
Advertisements