PHP Functions

A function is a block of code that can perform a specific task when called. PHP provides two major types of functions: built-in and user-defined. They are useful as they help in carrying out repetitive tasks without repeating the code. In this article, we will discuss Functions in PHP. Also, we will discuss various examples of declaring and invoking them.

Types of Functions in PHP

PHP has two major types of functions supported in PHP 5, PHP 7 and some older versions.

Built-In Functions

There are a number of built-in functions in PHP which are supported in PHP 5, PHP 7 and some older versions. We just need to call them as per our requirement. For instance, print_r, array_push, strstr, etc are some examples. Additionally, you can also learn more on PHP Array and PHP String Functions on Concatly.

User-Defined Functions

Also, it is very easy to create our own user-defined functions. You can call them anytime in order to perform a task.

Advantages of Using Functions

Using Functions is always beneficial while coding. These advantages of using functions do not only apply to PHP, but to all the languages.

  1. Code Reusability: If we want a particular block of code to execute multiple times, we should always put it in a function. This helps in increasing code reusability.
  2. Code Readability: Since we avoid repeating code by using functions, they improve code readability. Our file is much smaller and easier to document.
  3. Reduced Coding Time: Also, they help in reducing the overall coding time. You can save the time spent on rewriting a piece of code again and again. Similarly, the time spent on debugging is reduced.

Creating User-Defined Functions in PHP

You can create your own functions to perform a specific task and call them as per requirement.

Syntax

<?php
	function functionName($parameter1, $parameter2 ... ) {
		//code goes here
	}
?>

Basic Points to Keep in Mind

You should have the following points in mind while declaring PHP functions.

  • The name of the function should not start from a number. However, it can start with a letter or underscore.
  • Function names are not case-sensitive. Therefore, lowercase and uppercase names are treated differently.
  • All the function declarations should always begin with the keyword ‘function’.

Always give a name to the function that reflects what it does.

Calling a Function in PHP

For instance, let’s create a simple function which prints a statement and call it.

<?php

	function printSomething() {
		echo 'Function Executed';
	}

	printSomething();

?>

You can call a function by the name followed by parentheses. In our example above, the function does not expect any parameters. It simply prints the statement.

OUTPUT:
Function Executed

Function Parameters in PHP

You can pass any number of variables in PHP functions as parameters. Parameters are information which the function expects when someone calls them. You can pass any number of variables separated by a comma in the function.

For instance, let’s create a function to find the sum of three integers.

<?php

	function calculateSum($number1, $number2, $number3) {
		$sum = $number1 + $number2 + $number3;
		echo 'The Sum of the numbers is '.$sum;
	}

	calculateSum(1, 2, 3);

?>

In the above example, we pass 3 numbers to the function as arguments and it prints the sum of the three numbers.

OUTPUT:
The Sum of the numbers is 6

Default Values Or Optional Parameters

Also, you can make some parameters optional by providing a default value to them in the function definition in PHP. If we do not pass any value to the corresponding parameter, the function will use the default value for it.

For instance, let’s change the calculate sum function to make two parameters mandatory and the third one optional.

<?php

	function calculateSum($number1, $number2, $number3 = 0) {
		$sum = $number1 + $number2 + $number3;
		echo 'The Sum of the numbers is '.$sum;
	}

	calculateSum(1, 2); //Third parameter assumed to be 0
	//3 

	calculateSum(1, 2, 3);
	//6
?>

We have made the third parameter optional by providing a default value of 0. Now, if we don’t provide the third parameter, the function assumes it to be 0.

Note: Always write the optional parameters on the right-hand side of the function definition. There should be no mandatory parameter after the optional parameter.

Returning Values from PHP Functions

Also, functions can return values to the part of the program which called it. You should use the return keyword to return something from the function. Functions in PHP can return integers, strings, arrays or any object. However, any code after the return statement is not executed and the control resumes back to the part which called it.

Returning Integers

For instance, let’s return the sum of three integers instead of printing it.

<?php

	function calculateSum($number1, $number2, $number3) {
		$sum = $number1 + $number2 + $number3;
		return $sum;
	}

	$returnedSum = calculateSum(10, 20, 30);
	echo 'The Returned Sum is: '.$returnedSum;
?>

You need to assign a variable to get the value which the function returns.

OUTPUT:
The Returned Sum is: 60

Returning Arrays

Similarly, PHP Functions can return arrays also. For example, consider the example below:

<?php

	function calculateTwice($array) {
		for($i = 0; $i < count($array); $i++) {
			$array[$i] = $array[$i] * 2;
		}
		return $array;
	}

	$inputArray = array(1, 2, 3);
	$twiceArray = calculateTwice($inputArray);
	print_r($twiceArray);

?>

In the example, the function calculates twice of all the elements of the array in PHP. The calculateTwice function in PHP returns the final array.

OUTPUT:
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

PHP Functions Call By Value and Call By Reference

PHP allows us to pass arguments in two different ways to functions.

  • Call By Value: When you pass a parameter by value, the value in the function changes. However, the original value outside the function remains the same. Therefore, there are two copies of the variable in the memory.
  • Call By Reference: On passing a parameter by reference, the original value is changed. Therefore, there is only one copy of the variable in memory. Also, class objects are always called by reference.

PHP Functions Call By Value

<?php

	function callByValue($num) {
		$num = $num + 2;
		echo 'The Value inside the function is: '.$num;
	}

	$num = 10;
	echo 'The Original Value is: '.$num;
	callByValue($num);
	echo 'The Value after function is: '.$num;

?>

On passing arguments by value, the function creates a separate copy of the variable to play with. It does not change the original value of the variable.

The Original Value is: 10
The Value inside the function is: 12
The Value after function is: 10

PHP Functions Call By Reference

<?php

	function callByValue(&$num) {
		$num = $num + 2;
		echo 'The Value inside the function is: '.$num;
	}

	$num = 10;
	echo 'The Original Value is: '.$num;
	callByValue($num);
	echo 'The Value after function is: '.$num;

?>

You can make a parameter call by reference by & keyword before the parameter name in functions in PHP. The original value of the parameter also changes.

OUTPUT
The Original Value is: 10
The Value inside the function is: 12
The Value after function is: 12

Class Objects are Always Call By Reference

Also, class objects are always called by reference in PHP Functions. This is because objects always have only one memory allocation for them.

<?php

	function sampleFunction(SampleClass $object) {
		$object->number = 20;
		echo 'The Value of Class Member in the Function: '.$object->number;
	}

	class SampleClass {
		public $number = 10;
	}	

	$sampleObject = new SampleClass();
	echo 'The Original Value of Class Member: '.$sampleObject->number;
	sampleFunction($sampleObject);
	echo 'The Final Value of the Class Member: '.$sampleObject->number;

?>
OUTPUT:
The Original Value of Class Member: 10
The Value of Class Member in the Function: 20
The Final Value of the Class Member: 20

You can read more on Classes and Objects on Concatly.

Conclusion

In conclusion, we discussed PHP Functions. Also, we discussed how to create and invoke functions. Moreover, we discussed returning values and different function parameters. You can read more on User-Defined Functions on PHP Official Documentation.

Spread the Knowledge
Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *