Functions in PHP

Functions are group of statements that can be executed (any number of times) by calling its name.

Functions can be created using function keyword followed by function name which is again followed by a pair of parenthesis. Inside parenthesis you can pass optional arguments.

Naming convention of function is same as that of variable names.

Syntax

//function definition
function function_name(optional args)
{
	statement 1;
	statement 2;
}

function_name(); //function call

Why to use function?

In programming, sometimes we need to repeat a code. Instead of writing a code again and again we can just convert that code into a function and then call it again and again whenever needed. Moreover it will become more easy to maintain our code by using functions.

Example

<?php

//defining function
function addition()
{
	$x = 1;
	$y = 3;
	$z = $x + $y;
	echo $z;
}

addition(); //4

?>

return keyword

functions can also return value to the caller using return keyword.

Syntax

<?php

function function_name(optional args)
{
	statement 1;
	statement 2;
	
        return result;
}

?>

Example for using for using return statement

<?php

function addition()
{
	$x = 1;
	$y = 3;
	$z = $x + $y;
	return $z;
}

$result = addition(); //function call

echo $result; //4

?>

Functions with arguments

We can pass one or more arguments inside a function. Passed arguments can be processed within the function to generate the output.

Example for using functions with arguments

<?php

function addition($x, $y)
{
	$z = $x + $y;
	return $z;
}

$result =  addition(10, 11); //function call

echo $result; //21

?>

When we call the function we pass two arguments. 10 is stored in $x and 11 is stored in $y. Then it is processed inside the function to give the output.

You can also give default values to arguments while defining the function. Doing so will give the variable a default value in case if some value is not provided to that variable while function call.

Note : Always put the arguments with default values to the right side of non-default arguments.

Example

<?php

#In function definition $x is placed to right of $y

function addition($y, $x=11)
{
	$z = $x + $y;
	return $z;
}

$result =  addition(11); //function call

echo $result; //22

?>
<< Variables and Data Types in PHP Variable Scope >>