SlideShare a Scribd company logo
1 of 11
PHP User-defined functions
PHP User-defined functions
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
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
<?php
//function definition
function sayHello()
{
echo "Hello World!";
}
//function call
sayHello();
?>
Output
Hello World!
function with arguments
<?php
function add($arg1, $arg2){
echo $arg1+$arg2 . "n";
}
add(10,20);
add("Hello", "World");
?>
Example
Output
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 returns a value to calling
environment
Example
<?php
function add($arg1, $arg2){
return $arg1+$arg2;
}
$val=add(10,20);
echo "addition:". $val. "n";
$val=add("10","20");
echo "addition: $val";
?>
Output
addition:30
addition:30
In second call, even if arguments are string, PHP coerces 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 argument
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
<?php
function welcome($user="Guest"){
echo "Hello $usern";
}
//overrides default
welcome("admin");
//uses default
welcome();
?>
Output
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
<?php
function add(...$numbers){
$ttl=0;
foreach ($numbers as $num){
$ttl=$ttl+$num;
}
return $ttl;
}
$total=add(10,15,20);
echo "total= $totaln";
echo "total=". add(1,2,3,4,5). "n";
?>
Output
total= 45
total=15
<?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= $totaln";
echo "total=". add(1,2,3,4,5). "n";
?>
Output
total= 45
total=15
It is also possible to obtain a list of arguments passed to a function with the help of func_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.
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
<?php
function hello(){
echo "Hellon";
function welcome(){
echo "Welcome to the world of programmingn";
}
}
//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
Hello
Welcome to the world of programming
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
<?php
function factorial($n){
if ($n < 2) {
return 1;
} else {
return ($n * factorial($n-1));
}
}
echo "factorial(5) = ". factorial(5);
?>
Output
factorial(5) = 120

More Related Content

What's hot

Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
CHAITALIUKE1
 
structure and union
structure and unionstructure and union
structure and union
student
 

What's hot (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Programming paradigm
Programming paradigmProgramming paradigm
Programming paradigm
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
structure and union
structure and unionstructure and union
structure and union
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 

Similar to php user defined functions

Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 

Similar to php user defined functions (20)

Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Function in c
Function in cFunction in c
Function in c
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
C function
C functionC function
C function
 
Function in c
Function in cFunction in c
Function in c
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Functions
FunctionsFunctions
Functions
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Array Cont
Array ContArray Cont
Array Cont
 
Functions1
Functions1Functions1
Functions1
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 

More from vishnupriyapm4

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHP
vishnupriyapm4
 

More from vishnupriyapm4 (19)

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHP
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptx
 
pccf unit 1 _VP.pptx
pccf unit 1 _VP.pptxpccf unit 1 _VP.pptx
pccf unit 1 _VP.pptx
 
Introduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxIntroduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptx
 
Entity_DBMS.pptx
Entity_DBMS.pptxEntity_DBMS.pptx
Entity_DBMS.pptx
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
Unit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptxUnit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptx
 
Unit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptxUnit 3_Numpy_VP.pptx
Unit 3_Numpy_VP.pptx
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
OPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxOPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptx
 
Open Source VP.pptx
Open Source VP.pptxOpen Source VP.pptx
Open Source VP.pptx
 
Project Planning and Management.pptx
Project Planning and Management.pptxProject Planning and Management.pptx
Project Planning and Management.pptx
 
Software_Process_Model for class.ppt
Software_Process_Model for class.pptSoftware_Process_Model for class.ppt
Software_Process_Model for class.ppt
 
2.java intro.pptx
2.java intro.pptx2.java intro.pptx
2.java intro.pptx
 
features of JAVA.pptx
features of JAVA.pptxfeatures of JAVA.pptx
features of JAVA.pptx
 
Session and cookies in php
Session and cookies in phpSession and cookies in php
Session and cookies in php
 
constant in C
constant in Cconstant in C
constant in C
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Break and continue in C
Break and continue in C Break and continue in C
Break and continue in C
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

php user defined functions

  • 2. PHP User-defined functions 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
  • 3. 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.
  • 4. user defined function Example <?php //function definition function sayHello() { echo "Hello World!"; } //function call sayHello(); ?> Output Hello World!
  • 5. function with arguments <?php function add($arg1, $arg2){ echo $arg1+$arg2 . "n"; } add(10,20); add("Hello", "World"); ?> Example Output 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.
  • 6. function return User defined function in following example processes the provided arguments and returns a value to calling environment Example <?php function add($arg1, $arg2){ return $arg1+$arg2; } $val=add(10,20); echo "addition:". $val. "n"; $val=add("10","20"); echo "addition: $val"; ?> Output addition:30 addition:30 In second call, even if arguments are string, PHP coerces them into integer and performs addition
  • 7. function with default argument value While defining a function , a default value of argument may be assigned. If value is not assigned to such argument 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 <?php function welcome($user="Guest"){ echo "Hello $usern"; } //overrides default welcome("admin"); //uses default welcome(); ?> Output Hello admin Hello Guest In second call, function is called without passing value. In this case, user argument takes its default value.
  • 8. 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 <?php function add(...$numbers){ $ttl=0; foreach ($numbers as $num){ $ttl=$ttl+$num; } return $ttl; } $total=add(10,15,20); echo "total= $totaln"; echo "total=". add(1,2,3,4,5). "n"; ?> Output total= 45 total=15
  • 9. <?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= $totaln"; echo "total=". add(1,2,3,4,5). "n"; ?> Output total= 45 total=15 It is also possible to obtain a list of arguments passed to a function with the help of func_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.
  • 10. 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 <?php function hello(){ echo "Hellon"; function welcome(){ echo "Welcome to the world of programmingn"; } } //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 Hello Welcome to the world of programming
  • 11. 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 <?php function factorial($n){ if ($n < 2) { return 1; } else { return ($n * factorial($n-1)); } } echo "factorial(5) = ". factorial(5); ?> Output factorial(5) = 120