To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the user of functional cookies. For more information read this page.

Functions in PHP

A function in programming is something that does something else when given some input.

In the case of PHP, a function can be any block of code that can take any number of parameters and return 0 or 1 values.

Because of the way that PHP interacts with the webpage it is generating however, the function can directly write content on to the page using echo and print.

When a function is used, it is called:

PHP
<?php
	test();
?>
		

Defining a function

A function is defined by the keyword function followed by some string of characters:

PHP
<?php
	function test() {
		print($x);
	}
?>
		

Parameters

Parameters are values that are given in to the function directly on the function call. They are defined in the function declaration in the brackets after the name of the function. Parameters should be separated using commas. The following example demonstrates a function with parameters:

PHP
<?php
	function test($x, $y) {
		print($x * $y);
	}
?>
		

This function has two parameters, $x and $y.

This now changes the original function call to one that takes two parameters, for instance, the values 5 and 2:

PHP
<?php
	test(5, 2);
?>
		

Return a value

In programming in general, functions are designed to send back values. PHP is no different with this but functions are not necessarily expected to send back a value.

Sending back a value is known as returning a value.

Returning a value in PHP is done with the return command.

PHP
<?php
	function test($x, $y) {
		return $x * $y;
	}
?>
		

The return function does not need brackets around the return value.