SlideShare a Scribd company logo
UNIT-2
FUNCTIONS IN PHP
What is a Function in PHP
• A Function in PHP is a reusable piece or block of code that
performs a specific action.
function in php like control loop and its uses
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
function in php like control loop and its uses
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
•A function is a block of statements that can be used repeatedly in a
program.
•A function will not execute automatically when a page loads.
•A function will be executed by a call to the function.
Why use Functions?
•Better code organization – PHP functions allow us to group blocks of
related code that perform a specific task together.
•Reusability – once defined, a function can be called by a number of scripts
in our PHP files. This saves us time of reinventing the wheel when we want
to perform some routine tasks such as connecting to the database
•Easy maintenance- updates to the system only need to be made in one
place.
<?php
function hello()
{
echo" hello everybody";
}
hello();
hello();
echo" hi hw r u";
hello();
?>
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.
Easy to understand: PHP functions separate the programming logic. So it
is easier to understand the flow of the application because every logic is
divided in the form of functions.
function in php like control loop and its uses
PHP Function Arguments
• Information can be passed to functions through arguments. An
argument is just like a variable.
• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
function in php like control loop and its uses
function in php like control loop and its uses
<?php
function hello($name,$lname)
{
echo"hello $name,$lname.<br>";
}
hello(“Anil","kumar");
hello(“Ajay",“Sharma");
?>
function in php like control loop and its uses
Write a function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.
<?php
function
factorial_of_a_number($n)
{
if($n ==0)
{
return 1;
}
else
{
return $n *
factorial_of_a_number($n-1);
}
}
print_r(factorial_of_a_number(4)
."n");
?>
function in php like control loop and its uses
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
PHP strict typing
• In this example, the add() function
accepts two integers and returns the
sum of them.
• However, when you pass two floats
1.5 and 2.5, the add() function
returns 3 because PHP implicitly
coerces the values to the target types
by default.
• In this case, PHP coerces the floats
into integers.
• To enable strict typing, you can use
the declare (strict_types=1); directive
at the beginning of the file.
• To enable strict typing, you can use the declare(strict_types=1);
• By adding the strict typing directive to the file, the code will
execute in the strict mode. PHP enables the strict mode on a
per-file basis.
• In the strict mode, PHP expects the values with the type
matching with the target types. If there’s a mismatch, PHP will
issue an error.
function in php like control loop and its uses
<?php
Function hello($name="first",$lname="last")
{
Echo "hello $name,$lname.<br>";
}
hello("deepinder");
hello(“kiran",“deep");
?>
<?php
function hello($name="first",
$lname="last")
{
echo"hello $name,$lname.<br>";
}
function sum($a,$b)
{
echo $a+$b;
}
hello("deepinder");
hello("renu","dhiman");
sum(10,20);
?>
<?php
function add($n1=10,$n2=10)
{
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:
•Pass by Value: On passing arguments using pass by value, the value of the
argument gets changed within a function, but the original value outside the
function remains unchanged. That means a duplicate of the original value is
passed as an argument.
•Pass by Reference: On passing arguments as pass by reference, the original
value is passed. Therefore, the original value gets altered. In pass by reference we
actually pass the address of the value, where it is stored using ampersand
sign(&).
function in php like control loop and its uses
function in php like control loop and its uses
<?php
function
testing($string)
{
$string.="hello";
}
$str="this is string";
testing($str);
echo $str;
?>
Call by Value
<?php
function testing(&$string)
{
$string.="hello";
}
$str="this is string";
testing($str);
echo $str;
?>
Call by Reference
<!DOCTYPE html>
<html>
<body>
<?php function adder(&$x)
{
$x .= ' This is Call By Reference ';
}
$y = 'Hello PHP.';
adder($y); echo $y;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function incre(&$i)
{
$i++;
}
$i = 1;
incre($i);
echo $i;
?>
</body>
</html>
OUTPUT
?
CALL BY VALUE
<!DOCTYPE html>
<html>
<body>
<?php function adder($x)
{
$x .= 'Call By Value';
}
$y = 'Hello PHP';
adder($y);
echo $y;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function incre($i)
{
$i++;
}
$i = 1;
incre($i);
echo $i;
?>
</body>
</html>
OUTPUT
?
RECURSIVE FUNCTION
<?php
function display($number)
{
if($number<=5)
{
echo "$number <br>";
display($number + 1);
}
}
display(1);
?>
<html>
<body>
<?php function NaturalNumbers($number)
{
if($number<=10)
{
echo "$number <br/>";
NaturalNumbers($number+1);
}
}
NaturalNumbers(1);
?>
</body>
</html>
PHP Default Parameters
• The following defines the concat() function that concatenates two strings
with a delimiter:
• -PHP allows you to specify a default argument for a parameter.
For example:
• In this example, the $delimiter parameter takes the space as
the default argument.
PHP Anonymous Functions
• When you define a function, you specify a name for it. Later, you can call the
function by its name.
• For example, to define a function that multiplies two numbers, you
can do it as follows:
• An anonymous function is a function that doesn’t have a name.
• The following example defines an anonymous function that
multiplies two numbers:
1. Code to generate factorial of a number using recursive function in PHP.
TRY THIS
2. Write a program to print numbers from 10 to 1 using the
recursion function.

More Related Content

Similar to function in php like control loop and its uses (20)

PPT
PHP-03-Functions.ppt
ShishirKantSingh1
 
PPT
Class 3 - PHP Functions
Ahmed Swilam
 
PPTX
Functuon
NithyaNithyav
 
PPTX
Functuon
NithyaNithyav
 
PPTX
advancing in php programming part four.pptx
KisakyeDennis
 
PDF
Php, mysq lpart3
Subhasis Nayak
 
PPT
php 2 Function creating, calling, PHP built-in function
tumetr1
 
PPT
Understanding PHP Functions: A Comprehensive Guide to Creating
jinijames109
 
PPT
PHP - Introduction to PHP Functions
Vibrant Technologies & Computers
 
PDF
4.2 PHP Function
Jalpesh Vasa
 
PDF
Hsc IT 5. Server-Side Scripting (PHP).pdf
AAFREEN SHAIKH
 
PDF
Web app development_php_06
Hassen Poreya
 
PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
PDF
Functional Programming in PHP
pwmosquito
 
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
PPTX
Php operators
Aashiq Kuchey
 
PDF
PHP Lec 2.pdfsssssssssssssssssssssssssss
ksjawyyy
 
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
DeepakUlape2
 
PPTX
Php functions
JIGAR MAKHIJA
 
PHP-03-Functions.ppt
ShishirKantSingh1
 
Class 3 - PHP Functions
Ahmed Swilam
 
Functuon
NithyaNithyav
 
Functuon
NithyaNithyav
 
advancing in php programming part four.pptx
KisakyeDennis
 
Php, mysq lpart3
Subhasis Nayak
 
php 2 Function creating, calling, PHP built-in function
tumetr1
 
Understanding PHP Functions: A Comprehensive Guide to Creating
jinijames109
 
PHP - Introduction to PHP Functions
Vibrant Technologies & Computers
 
4.2 PHP Function
Jalpesh Vasa
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
AAFREEN SHAIKH
 
Web app development_php_06
Hassen Poreya
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Functional Programming in PHP
pwmosquito
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
Php operators
Aashiq Kuchey
 
PHP Lec 2.pdfsssssssssssssssssssssssssss
ksjawyyy
 
Introduction to PHP_ Lexical structure_Array_Function_String
DeepakUlape2
 
Php functions
JIGAR MAKHIJA
 

More from vishal choudhary (20)

PPTX
Pixel to Percentage conversion Convert left and right padding of a div to per...
vishal choudhary
 
PPTX
esponsive web design means that your website (
vishal choudhary
 
PPTX
function in php using like three type of function
vishal choudhary
 
PPTX
data base connectivity in php using msql database
vishal choudhary
 
PPTX
software evelopment life cycle model and example of water fall model
vishal choudhary
 
PPTX
software Engineering lecture on development life cycle
vishal choudhary
 
PPTX
strings in php how to use different data types in string
vishal choudhary
 
PPTX
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
PPTX
web performnace optimization using css minification
vishal choudhary
 
PPTX
web performance optimization using style
vishal choudhary
 
PPTX
Data types and variables in php for writing and databse
vishal choudhary
 
PPTX
Data types and variables in php for writing
vishal choudhary
 
PPTX
Data types and variables in php for writing
vishal choudhary
 
PPTX
sofwtare standard for test plan it execution
vishal choudhary
 
PPTX
Software test policy and test plan in development
vishal choudhary
 
PPTX
introduction to php and its uses in daily
vishal choudhary
 
PPTX
data type in php and its introduction to use
vishal choudhary
 
PPTX
PHP introduction how to create and start php
vishal choudhary
 
PPT
SE-Lecture1.ppt
vishal choudhary
 
PPT
SE-Testing.ppt
vishal choudhary
 
Pixel to Percentage conversion Convert left and right padding of a div to per...
vishal choudhary
 
esponsive web design means that your website (
vishal choudhary
 
function in php using like three type of function
vishal choudhary
 
data base connectivity in php using msql database
vishal choudhary
 
software evelopment life cycle model and example of water fall model
vishal choudhary
 
software Engineering lecture on development life cycle
vishal choudhary
 
strings in php how to use different data types in string
vishal choudhary
 
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
web performnace optimization using css minification
vishal choudhary
 
web performance optimization using style
vishal choudhary
 
Data types and variables in php for writing and databse
vishal choudhary
 
Data types and variables in php for writing
vishal choudhary
 
Data types and variables in php for writing
vishal choudhary
 
sofwtare standard for test plan it execution
vishal choudhary
 
Software test policy and test plan in development
vishal choudhary
 
introduction to php and its uses in daily
vishal choudhary
 
data type in php and its introduction to use
vishal choudhary
 
PHP introduction how to create and start php
vishal choudhary
 
SE-Lecture1.ppt
vishal choudhary
 
SE-Testing.ppt
vishal choudhary
 
Ad

Recently uploaded (20)

PDF
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
PDF
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PPTX
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PPTX
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
PDF
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
PPTX
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PDF
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
PDF
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Ad

function in php like control loop and its uses