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

PPTX
function in php using like three type of function
PPTX
Functions in PHP.pptx
PPT
PHP-03-Functions.ppt
PPT
PHP-03-Functions.ppt
PPTX
UNIT- 2 Functions__________________.pptx
PPT
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
PPTX
PHP FUNCTIONS AND ARRAY.pptx
PPTX
Web Application Development using PHP Chapter 3
function in php using like three type of function
Functions in PHP.pptx
PHP-03-Functions.ppt
PHP-03-Functions.ppt
UNIT- 2 Functions__________________.pptx
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
PHP FUNCTIONS AND ARRAY.pptx
Web Application Development using PHP Chapter 3

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

PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
PPT
Introduction To Php For Wit2009
PPT
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
PPT
Php i basic chapter 3
PPT
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
PDF
PHP Lec 2.pdfsssssssssssssssssssssssssss
PPTX
Arrays &amp; functions in php
PDF
Introduction to PHP - Basics of PHP
PPTX
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT II (7).pptx
PPTX
UNIT II (7).pptx
PDF
4.2 PHP Function
PPT
PHP - Introduction to PHP Functions
PDF
Introduction to PHP_Slides by Lesley_Bonyo.pdf
PDF
What's new in PHP 8.0?
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
Introduction To Php For Wit2009
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
PHP Lec 2.pdfsssssssssssssssssssssssssss
Arrays &amp; functions in php
Introduction to PHP - Basics of PHP
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT II (7).pptx
UNIT II (7).pptx
4.2 PHP Function
PHP - Introduction to PHP Functions
Introduction to PHP_Slides by Lesley_Bonyo.pdf
What's new in PHP 8.0?
Ad

More from vishal choudhary (20)

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

Recently uploaded (20)

PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
English Language Teaching from Post-.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Business Ethics Teaching Materials for college
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Insiders guide to clinical Medicine.pdf
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Week 4 Term 3 Study Techniques revisited.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
English Language Teaching from Post-.pdf
Pre independence Education in Inndia.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Business Ethics Teaching Materials for college
Abdominal Access Techniques with Prof. Dr. R K Mishra
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
Insiders guide to clinical Medicine.pdf
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)

function in php like control loop and its uses