Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.1Functions in PHP

A function in computer programming is something that does performs some operation, process or calculation on some given input and often gives back (returns) a result.

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 identifier:

PHP
<?php
	function test() {
		print("Hello world!");
	}
	test();
?>
		

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);
	}
	test(5, 5);
?>
		

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

This now changes the original function call to one that takes two parameters. This code was tested with the parameters 5 and 5, but it can be run over and over again without being redefined, for instance with 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;
	}
	print("The result of the function is:");
	print(test(5, 2));
?>
		

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

Feedback 👍
Comments are sent via email to me.