0% found this document useful (0 votes)
13 views16 pages

Function PHP

Uploaded by

rkdevi282022
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views16 pages

Function PHP

Uploaded by

rkdevi282022
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

https://l.instagram.com/?u=https%3A%2F%2Ftamilyogi2.

cam
%2Fmovies%2Fwatch-manjummel-boys-malayalam-hd
%2F&e=AT0kl0LDBOlq-NnqZq3N6dw-
a35AdYFgQCu1SQR2v46wBJSRsgOmYzWUh8SST0gY8TresKTHrEs1h1ql
ghnTdAhVyJSZizR7-
YkpbPhWKB5fSgS4tZhnX0dMb1pehhrx7o9wKSTQFRJU4Tx2Dms4QQ

A function is a block of code written in a program to perform some


specific task. We can relate functions in programs to employees in a
office in real life for a better understanding of how functions work.
Suppose the boss wants his employee to calculate the annual budget.
So how will this process complete? The employee will take information
about the statistics from the boss, performs calculations and calculate
the budget and shows the result to his boss. Functions works in a
similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns
the result.
PHP provides us with two major types of functions:

 Built-in functions : PHP provides us with huge collection of built-in


library functions. These functions are already coded and stored in
form of functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype() and so on.
 User Defined Functions : Apart from the built-in functions, PHP
allows us to create our own customised functions called the user-
defined functions.
Using this we can create our own packages of code and use it
wherever necessary by simply calling it.
Why should we use functions?

 Reusability: If we have a common code that we would like to use


at various parts of a program, we can simply contain it within a
function and call it whenever required. This reduces the time and
effort of repetition of a single code. This can be done both within a
program and also by importing the PHP file, containing the function,
in some other program
 Easier error detection: Since, our code is divided into functions,
we can easily detect in which function, the error could lie and fix
them fast and easily.
 Easily maintained: As we have used functions in our program, so
if anything or any line of code needs to be changed, we can easily
change it inside the function and the change will be reflected
everywhere, where the function is called. Hence, easy to maintain.

Creating a Function

While creating a user defined function we need to keep few things in


mind:

1. Any name ending with an open and closed parenthesis is a function.


2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the
parenthesis
4. A function name cannot start with a number. It can start with an
alphabet or underscore.
5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}
Example:

 PHP

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

return $product; //returning the product

// storing the returned value

$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";

?>

Output:
This is Geeks for Geeks

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are


called parameters. These are used to hold the values executable
during runtime. A user is free to take in as many parameters as he
wants, separated with a comma(,) operator. These parameters are
used to accept inputs during runtime. While passing the values like
during a function call, they are called arguments. An argument is a
value passed to a function and a parameter is used to hold those
arguments. In common term, both parameter and argument mean the
same. We need to keep in mind that for every parameter, we need to
pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:

 PHP

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

{
$product = $num1 * $num2 * $num3;

echo "The product is $product";

// Calling the function

// Passing three arguments

proGeek(2, 3, 5);

?>

Output:

The product is 30

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters.


If we do not pass any argument for a parameter with default value
then PHP will use the default set value for this parameter in the
function call.
Example:

 PHP

<?php
// function with default parameter

function defGeek($str, $num=12)

echo "$str is $num years old \n";

// Calling the function

defGeek("Ram", 15);

// In this call, the default value 12

// will be considered

defGeek("Adam");

?>

Output:

Ram is 15 years old


Adam is 12 years old

In the above example, the parameter $num has a default value 12, if
we do not pass any value for this parameter in a function call then this
default value 12 will be considered. Also the parameter $str has no
default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is
called. The return keyword is used to return value back to the part of
program, from where it was called. The returning value may be of any
type including the arrays and objects. The return statement also marks
the end of the function and stops the execution after that and returns
the value.
Example:

 PHP

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

return $product; //returning the product

// storing the returned value


$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";

?>

Output:

The product is 30

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(&).

Example:

 PHP

<?php
// pass by value

function valGeek($num) {

$num += 2;

return $num;

// pass by reference

function refGeek(&$num) {

$num += 10;

return $num;

$n = 10;

valGeek($n);

echo "The original value is still $n \n";

refGeek($n);
echo "The original value changes to $n";

?>

Output:

The original value is still 10


The original value changes to 20

PHP Function arguments


PHPServer Side ProgrammingProgramming

Introduction
A function in PHP can be defined to accept input from calling environment/script
in the form of arguments. These arguments are given as comma separeted list
inside the parentheses in front of name of function. Note that while calling a
function, same number of arguments must be passed to it.

PHP supports calling a function by passing value, reference, arguments with


default value and by passing variable number of arguments.

function with arguments


In following example, a function is defined with two formal arguments. When
this function is called by passing the arguments by value. Arguments of function
become its local variables. Hence, any change in value of argument inside a
function doesn't reflect outside it.

Here, value of $x is changed inside the function, but if we check its value after
call to function, it has not changed

Example
Live Demo

<?php
function add($x, $y){
$x= $x+$y ;
echo $x . "
";
}
$x=10;
$y=20;
add($x,$y);
//outside function $x has previous value.
echo $x;
?>

Output
This will produce following result. −

30
10

Passing array to function


In following example, add() function is defined to receive array as argument.
Inside the function, array elements are traversed using foreach loop

Example
Live Demo
<?php
function add($arr){
$sum=0;
foreach ($arr as $i){
$sum+=$i;
}
echo "sum = " .$sum;
}
add(array(1,2,3));
?>

Output
This will produce following result. −

sum = 6

Passing arguments by reference


Values are passed to a function's arguments by value. Hence, changes to
argument's value inside function are not reflected outside it. When arguments
are passed by reference, changes are carried to the argument's value outside it.

In order to receive value by reference, the argument's name must be prefixed


by $ symbol

Example
Live Demo

<?php
function swap(&$x, &$y){
$t=$x;
$x=$y;
$y=$t;
echo "inside function x=$x y=$y
";
}
$x=5;
$y=7;
echo "before calling function x=$x y=$y
";
swap($x, $y);
echo "after calling function x=$x y=$y
";
?>

Output
This will produce following result. −

before calling function x=5 y=7


inside function x=7 y=5
after calling function x=7 y=5

Values of variables xand����y are interchanged in swap() function. Since,


variables are passed by reference, the variables show modified values outside
the function too

Type hints (Type declarations)


PHP in fact is a dynamically typed language. Hence, it is not necessary to
declare a variable with its type (as in C/C++ or Java). However, type declaration
of arguments in a function llows the parser to detect incorrect data types passed
to the function.

Syntax
//define a function with type hints
function myfunction(type $arg1, type $arg2){
..
..
}

All standard PHP data types including scalar types, array, class/interface,
iterable and object are valid types for providing type hints in a function
declaration
Example
Live Demo

<?php
function add(...$numbers){
$ttl=0;
foreach ($numbers as $num){
$ttl=$ttl+$num;
}
return $ttl;
}
$total=add(10,15,20);
echo "total= $total
";
echo "total=". add(1,2,3,4,5). "
";
?>

Output
This will produce following result. −

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.

Example
Live Demo

<?php
function add (int $x, int $y){
$z=$x+$y;
echo "addition=$z
";
}
add(10,20);
add(5.55, 6.66);
?>

Output
This will produce following result. −

addition=30
addition=11

Note that in second call to add() function, floats are given as arguments, but still
no error/warning is displayed. This is because PHP internally coerces float into
integer for performing addition. In order to prevent such automatic type
conversion, use declareconstruct with strict_types=1

Example
Live Demo

<?php
declare(strict_types=1);
function add (int $x, int $y){
$z=$x+$y;
echo "addition=$z
";
}
add(10,20);
add(5.55, 6.66);
?>

Second call to add() function will now throw exception −

Output
addition=30
PHP Fatal error: Uncaught TypeError: Argument 1 passed to add() must be

You might also like