SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente (20)

Php array
Php arrayPhp array
Php array
 
Php
PhpPhp
Php
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Html forms
Html formsHtml forms
Html forms
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
 
Sessions and cookies in php
Sessions and cookies in phpSessions and cookies in php
Sessions and cookies in php
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
CSS
CSS CSS
CSS
 

Similar a php user defined functions

Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptxJapneet9
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxShaliniPrabakaran
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
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).pptxvekariyakashyap
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdfNehaSpillai1
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7Rumman Ansari
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptxSulekhJangra
 
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?Nikita Popov
 

Similar a 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?
 

Más de vishnupriyapm4

introduction to web programming using PHP
introduction to web programming using PHPintroduction to web programming using PHP
introduction to web programming using PHPvishnupriyapm4
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxvishnupriyapm4
 
Introduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxIntroduction to DBMS_VP.pptx
Introduction to DBMS_VP.pptxvishnupriyapm4
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
OPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxOPS Ecosystem and Engineering.pptx
OPS Ecosystem and Engineering.pptxvishnupriyapm4
 
Project Planning and Management.pptx
Project Planning and Management.pptxProject Planning and Management.pptx
Project Planning and Management.pptxvishnupriyapm4
 
Software_Process_Model for class.ppt
Software_Process_Model for class.pptSoftware_Process_Model for class.ppt
Software_Process_Model for class.pptvishnupriyapm4
 
Session and cookies in php
Session and cookies in phpSession and cookies in php
Session and cookies in phpvishnupriyapm4
 
Break and continue in C
Break and continue in C Break and continue in C
Break and continue in C vishnupriyapm4
 

Más de 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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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