PHP Functions
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
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.
ADVERTISEMENT
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
Output:
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the
function.
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
Output:
The 3 dot concept is implemented for variable length argument since PHP 5.6.
File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
By default, value passed to the function is call by value. To pass value as a reference,
you need to use ampersand (&) symbol before the argument name.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
ADVERTISEMENT
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
display(1);
?>
Output:
1
2
3
4
5
echo factorial(5);
?>
Output: