PHP Functions

A function is a block of code for performing specific task. Function can be reused many times.

PHP function can take arguments as input and returns value.

PHP Built-in Functions

There are thousands of built-in functions are available in PHP which is for a specific task, like print_r(), var_dump(), etc.

PHP User-defined Functions

Below is the syntax of defining user-defined function.

Syntax

function functionname(){ 
//code to be executed 
}
Note: PHP user defined function name must start with a letter or underscore like other lebels in PHP. The name should not start with numbers or special symbols.

PHP Functions Example

<?php 
function sayWelcome(){ 
echo "Welcome to Tutorialsbook!"; 
} 
sayWelcome();//calling function 
?>

Output

Welcome to Tutorialsbook!

PHP Function Arguments

You can pass value to the function in the form of arguments. You can pass as many as parameters you like. These parameters are work like placeholder inside function.

PHP supports call by value (default), call by reference , default argument value and dynamic function call.

The below example takes 2 arguments and add them and then print them.

Example 

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(15, 10);
?>

Output

25

PHP Call By Reference

In general, the value passed inside the functions as arguments does not change (Call By Value). In PHP Call By Reference, you can pass the reference of a variable instead of actual value. In this case, the value of the variable will change with the change of argument.

You can pass value as a reference, you need to use ampersand(&) before the variable name.

Let’s see an example of PHP Call By Reference.

Example

<?php
function SelfAddition(&$num){
$num += $num;
return $num;
}

$mynum = 10;
echo $mynum;
echo "<br/>";

SelfAddition($mynum);
echo $mynum;
?>

Output

10
20

PHP Functions: Default Argument Value

A default value can be set for the argument passed in PHP function. Once you define the default value and later on if you are calling PHP function without passing any argument, it will take the argument.

Let understand the concept of Default Argument Value with the following example.

Example

<?php 
function welcomemsg($name="Guest"){ 
echo "Welcome $name<br/>"; 
} 
welcomemsg("Sagar"); 
welcomemsg();//passing no value 
welcomemsg("Avijit"); 
?>

Output

Welcome Sagar
Welcome Guest
Welcome Avijit

PHP Functions: Returning Values

A PHP function can return value using the return statement. It is generally the last statement inside a function and stops the execution of the function and provides control backs to the calling code.

If you want to return more than one value, you can do it by using return array(1,2,3);

Example

<?php 
function cube($n){ 
return $n*$n*$n; 
} 
echo "Cube of 4 is: ".cube(4); 
?>

Output

Cube of 4 is: 64

Please get connected & share!

Advertisement