Functions in PHP

Functions in PHP are used to encapsulate that piece of code which needs to be executed multiple times at different locations within the code. A function consists of two parts: Function declaration and Function call. Function declaration consist of defining the name of the function, the parameter which it receives, the code it executed and the value returned by the function. The function call is the place where the code within the function is executed. Have a look at the following example to understand functions

<?php
	// Creating a function
	function displayname(){
		echo "The name of the fucntion is displayname";
	}

	// Calling a function
	displayname();
?>

Download the code Run the code

In the above example a function “displayname” has been created which when called display a random string on the webpage. This function doesn’t receive any parameter and has no return type.

Passing Parameter to the function

A function can receive values from the calling function and can perform some functionality upon them. These values are received in the form of parameters. Function parameters are defined inside the parenthesis after the function name and these parameters are separated by comma. In the function call, the value for these parameters is passed. Have a look at the following example to see how parameters are passed to function

<?php

	// Creating a function
	function calculatesum($val1, $val2){
		echo "The sum of two numbers is ".($val1 + $val2);
	}

	// Calling a function
	calculatesum(5,5);
?>

Download the code Run the code

In the above code a function calculatesum has been declared which received two parameters. Inside the function the sum of these two passed parameters has been displayed. In the function call, the value 5 and 5 for two parameter is passed inside the parenthesis after the name of the function. When the function is called with these values, 10 will be displayed as sum.

Returning Values from Function

To return values from a function keyword return is used. Let’s modify the calculatesum function so that instead of displayed the sum inside the function, the function returns that value to the function call where the sum would be displayed.

<?php

	// Creating a function which returns some value
	function calculatesum ($val1, $val2){
		
		$result = ($val1 + $val2);
		return $result;
	}

	// Calling a function
	echo "The sum of two numbers is ".calculatesum(10,30);
?>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .