SlideShare a Scribd company logo
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

Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
C functions
C functionsC functions
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Pointer in c
Pointer in cPointer in c
Pointer in c
Imamul Kadir
 
Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 

What's hot (20)

Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
python Function
python Function python Function
python Function
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Call by value
Call by valueCall by value
Call by value
 
Files in php
Files in phpFiles in php
Files in php
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
php
phpphp
php
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
C functions
C functionsC functions
C functions
 
Data types in php
Data types in phpData types in php
Data types in php
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Php string function
Php string function Php string function
Php string function
 
structure and union
structure and unionstructure and union
structure and union
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 

Similar to php user defined functions

Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
Japneet9
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
C function
C functionC function
C function
thirumalaikumar3
 
Function in c
Function in cFunction in c
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).pptx
vekariyakashyap
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
Acácio Oliveira
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
Functions
FunctionsFunctions
Functions
zeeshan841
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Chandrakant Divate
 
Array Cont
Array ContArray Cont
Functions1
Functions1Functions1
Functions1
DrUjwala1
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
Aftabali702240
 

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
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.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
 

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

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 

Recently uploaded (20)

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 

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